Tar Filesystem

Manage the filesystem in a Tar archive.

class fs.tarfs.TarFS(wrap_fs)

Read and write tar files.

There are two ways to open a TarFS for the use cases of reading a tar file, and creating a new one.

If you open the TarFS with write set to False (the default), then the filesystem will be a read only filesystem which maps to the files and directories within the tar file. Files are decompressed on the fly when you open them.

Here’s how you might extract and print a readme from a tar file:

with TarFS('foo.tar.gz') as tar_fs:
    readme = tar_fs.gettext('readme.txt')

If you open the TarFS with write set to True, then the TarFS will be a empty temporary filesystem. Any files / directories you create in the TarFS will be written in to a tar file when the TarFS is closed. The compression is set from the new file name but may be set manually with the compression argument.

Here’s how you might write a new tar file containing a readme.txt file:

with TarFS('foo.tar.xz', write=True) as new_tar:
    new_tar.settext(
        'readme.txt',
        'This tar file was written by PyFilesystem'
    )
Parameters:
  • file (str or io.IOBase) – An OS filename, or an open file handle.
  • write (bool) – Set to True to write a new tar file, or use default (False) to read an existing tar file.
  • compression (str, optional) – Compression to use (one of the formats supported by tarfile: xz, gz, bz2, or None).
  • temp_fs (str) – An FS URL for the temporary filesystem used to store data prior to tarring.
class fs.tarfs.WriteTarFS(file, compression=None, encoding=u'utf-8', temp_fs=u'temp://__tartemp__')

A writable tar file.

write_tar(file=None, compression=None, encoding=None)

Write tar to a file.

Parameters:
  • file (str or io.IOBase, optional) – Destination file, may be a file name or an open file object.
  • compression (str, optional) – Compression to use (one of the constants defined in tarfile in the stdlib).
  • encoding (str, optional) – The character encoding to use (default uses the encoding defined in __init__).

Note

This is called automatically when the TarFS is closed.

class fs.tarfs.ReadTarFS(**kwargs)

A readable tar file.