view sdf chemical file in python

To view an sdf chemical file in Python, you can use the RDKit library. Here's a sample code that shows how to load and view an sdf file:

main.py
from rdkit import Chem
from rdkit.Chem import rdMolDraw2D

# Load the sdf file
molsuppl = Chem.SDMolSupplier('file.sdf')

# Get the first molecule
mol = molsuppl[0]

# Create a 2D drawing of the molecule
drawer = rdMolDraw2D.MolDraw2DSVG(400, 200)
drawer.DrawMolecule(mol)
drawer.FinishDrawing()

# Get the SVG string
svg = drawer.GetDrawingText()

# Print the SVG string
print(svg)
383 chars
20 lines

This code loads a sdf file using Chem.SDMolSupplier, which creates an iterable object that allows you to get individual molecules from the file. We then get the first molecule using [0].

We create a 2D drawing of the molecule using rdMolDraw2D.MolDraw2DSVG, which creates an SVG object that we can manipulate. We draw the molecule using drawer.DrawMolecule(mol) and finish the drawing using drawer.FinishDrawing().

Finally, we get the SVG string using drawer.GetDrawingText() and print it using print(svg). You can also write this SVG string to a file or display it in a web page.

gistlibby LogSnag