chemlab.io¶
This package contains utilities to read, write a variety of chemical file formats.
-
chemlab.io.
datafile
(filename, mode='rb', format=None)¶ Initialize the appropriate
IOHandler
for a given file extension or file format.The datafile function can be conveniently used to quickly read or write data in a certain format:
>>> handler = datafile("molecule.pdb") >>> mol = handler.read("molecule") # You can also use this shortcut >>> mol = datafile("molecule.pdb").read("molecule")
Parameters
- filename: str
- Path of the file to open.
- format: str or None
- When different from None, can be used to specify a format identifier for that file. It should be used when the extension is ambiguous or when there isn’t a specified filename. See below for a list of the formats supported by chemlab.
-
chemlab.io.
remotefile
(url, format=None)¶ The usage of remotefile is equivalent to
chemlab.io.datafile()
except you can download a file from a remote url.Example
mol = remotefile(“https://github.com/chemlab/chemlab-testdata/blob/master/3ZJE.pdb”).read(“molecule”)
The class IOHandler¶
-
class
chemlab.io.handlers.
IOHandler
(fd)¶ Generic base class for file readers and writers.
The initialization function takes a file-like object fd, as an argument.
Subclasses can extend the methods __init__, read and write to implement their reading and writing routines.
Attributes
-
fd
¶
-
can_read
¶ Type: list of str A list of features that the handler can read.
-
can_write
¶ Type: list of str A list of features that IOHandler can write.
-
check_feature
(feature, readwrite)¶ Check if the feature is supported in the handler and raise an exception otherwise.
Parameters
- feature: str
- Identifier for a certain feature.
- readwrite: “read” or “write”
- Check if the feature is available for reading or writing.
-
read
(feature, *args, **kwargs)¶ Read and return the feature feature. It should raise an ValueError if the feature is not present in the handler can_read attribute, use the method
IOHandler.check_feature()
to provide this behaviour.Certain features may require additional arguments, and it is possible to pass those as well.
Example
Subclasses can reimplement this method to add functionality:
class XyzIO(IOHandler): can_read = ['molecule'] def read(self, feature, *args, **kwargs): self.check_feature(feature, "read") if feature == 'molecule': # Do stuff return geom
-
write
(feature, value, *args, **kwargs)¶ Same as
read()
. You have to pass also a value to write and you may pass any additional arguments.Example
class XyzIO(IOHandler): can_write = ['molecule'] def write(self, feature, value, *args, **kwargs): self.check_feature(feature, "write") if feature == 'molecule': # Do stuff return geom
-