xopen

gmx.xopen(fname, mode='rt', fformat=None, **kwargs)[source]

Open a (compressed) file and return a corresponding file-like_object.

This function is a replacement for the built-in open() function that can additionally read and write compressed files. Supported compression formats:

  • gzip (.gz)

  • bzip2 (.bz2)

  • XZ/LZMA2 (.xz)

  • LZMA (.lzma)

Parameters:
  • fname (str or bytes or os.PathLike) – Name of the file to open.

  • mode ({'r', 'rt', 'rb', 'w', 'wt', 'wb', 'x', 'xt', 'xb', 'a', 'at', 'ab'}, optional) – Opening mode. See the built-in open() function for more details.

  • fformat ({None, 'gz', 'bz2', 'xz', 'lzma', 'uncompressed'}, optional) – Explicitly specify the file format. If None, the file format is guessed from the file name extension if present and otherwise from the file signature. If 'uncompressed', the file is treated as uncompressed file.

  • kwargs (dict, optional) – Additional keyword arguments to parse to the function that is used for opening the file. See there for possible arguments and their description.

Returns:

file (file-like object) – The opened file.

See also

open()

Function used to open uncompressed files

gzip.open()

Function used to open gzip-compressed files

bz2.open()

Function used to open bzip2-compressed files

lzma.open()

Function used to open XZ- and LZMA-compressed files

Notes

When writing and fformat is None, the compression algorithm is chosen based on the extension of the given file:

  • '.gz' uses gzip compression.

  • '.bz2' uses bzip2 compression.

  • '.xz' uses XZ/LZMA2 compression.

  • '.lzma' uses legacy LZMA compression.

  • otherwise, no compression is done.

When reading and fformat is None, the file format is detected from the file name extension if present. If no extension is present or the extension is unknown, the format is detected from the file signature, i.e. the first few bytes of the file also known as “magic numbers”.

References

Inspired by xopen by Marcel Martin, Ruben Vorderman et al.