zipfile

What it is good for?

Read and write .zip files.

You can add both existing files and strings to a zip file. If you are adding strings you need to specify the file name it is written to. When you extract files to a folder, the output folder is automatically created.

Installed with Python by default

yes

Example

Create a new zip archive and add files to it:

  1. import zipfile
  2. z = zipfile.ZipFile('archive.zip', 'w')
  3. z.write('myfile.txt') # has to exist
  4. z.writestr('test.txt', 'Hello World') # new
  5. z.close()

List contents of the newly created zip file:

  1. z = zipfile.ZipFile('archive.zip')
  2. print(z.namelist())

Extract a file to a new folder:

  1. print(z.extract('test.txt', 'myfolder'))
  2. z.close()

Where to learn more?

docs.python.org/3/library/zipfile.html