Zip Filesystem

Manage the filesystem in a Zip archive.

class fs.zipfs.ReadZipFS(file, encoding=u'utf-8')

A readable zip file.

class fs.zipfs.WriteZipFS(file, compression=8, encoding=u'utf-8', temp_fs=u'temp://__ziptemp__')

A writable zip file.

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

Write zip to a file.

Parameters:
  • file (str or io.IOBase, optional) – Destination file, may be a file name or an open file handle.
  • compression (str, optional) – Compression to use (one of the constants defined in the zipfile module 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 ZipFS is closed.

class fs.zipfs.ZipFS(wrap_fs)

Read and write zip files.

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

If you open the ZipFS 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 zip file. Files are decompressed on the fly when you open them.

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

with ZipFS('foo.zip') as zip_fs:
    readme = zip_fs.gettext('readme.txt')

If you open the ZipFS with write set to True, then the ZipFS will be a empty temporary filesystem. Any files / directories you create in the ZipFS will be written in to a zip file when the ZipFS is closed.

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

with ZipFS('foo.zip', write=True) as new_zip:
    new_zip.settext(
        'readme.txt',
        'This zip file was written by PyFilesystem'
    )
Parameters:
  • file (str or io.IOBase) – An OS filename, or an open file object.
  • write (bool, optional) – Set to True to write a new zip file, or False (default) to read an existing zip file.
  • compression (str, optional) – Compression to use (one of the constants defined in the zipfile module in the stdlib).
  • temp_fs (str, optional) – An FS URL for the temporary filesystem used to store data prior to zipping.