def read(f, format=None): """Read in a molecule from a file, file-like object, or string. Will also depickle a pickled object. Note: Files with ``.bz2`` or ``.gz`` suffixes will be automatically decompressed. Currently does not support files with more than one record - only returns the first record Args: f (str or file-like): Either a path to a file, OR a string with the file's contents, OR a file-like object format (str): molecule format (pdb, xyz, sdf, etc.) or pickle format (recognizes p, pkl, or pickle); guessed from filename if not passed Returns: moldesign.Molecule or object: molecule parsed from the file (or python object, for pickle files) Raises: ValueError: if ``f`` isn't recognized as a string, file path, or file-like object """ filename = None # Open a file-like object if isinstance(f, basestring) and os.path.exists(f): # it's a path to a file filename = f format, compression = _get_format(filename, format) fileobj = COMPRESSION[compression](filename, mode='r') elif hasattr(f, 'open'): # we can get a file-like object fileobj = f.open('r') elif hasattr(f, 'read'): # it's already file-like fileobj = f elif isinstance(f, basestring): # assume it's just a string if format is None: raise IOError( ('No file named "%s"; ' % f[:50]) + 'please set the `format` argument if you want to parse the string' ) fileobj = StringIO.StringIO(f) else: raise ValueError( 'Parameter to moldesign.read (%s) not ' % str(f) + 'recognized as string, file path, or file-like object') if format in READERS: mol = READERS[format](fileobj) else: # default to openbabel if there's not an explicit reader for this format mol = openbabel_interface.read_stream(fileobj, format) if filename is not None and mol.name not in (None, 'untitled'): mol.name = filename mdt.helpers.atom_name_check(mol) return mol
def read_xyz(f): tempmol = openbabel_interface.read_stream(f, 'xyz') for atom in tempmol.atoms: atom.residue = None atom.chain = None return mdt.Molecule(tempmol.atoms)