chemlab.io

This package contains utilities to read, write a variety of chemical file formats.

chemlab.io.datafile(filename, 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.

The class IOHandler

class chemlab.io.handlers.IOHandler(filename)

Generic base class for file readers and writers. The initialization function takes filename as input and sets the instance attribute filename.

Subclasses can extend the methods __init__, read and write to implement their reading and writing routines.

Attributes

filename
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

Project Versions

Table Of Contents

Previous topic

chemlab.core

Next topic

Supported File Formats

This Page