How to create a zip file using Python

Published on Aug. 22, 2023, 12:15 p.m.

To create a zip file using Python, you can use the built-in zipfile module. Here’s an example of how to create a zip file with a list of files:

import zipfile
my_files = ['file1.txt', 'file2.txt', 'file3.txt']
with zipfile.ZipFile('my_files.zip', 'w') as zip:
  for file in my_files:
    zip.write(file)

In this example, a list of files is defined in my_files, and a new zip file is created with zipfile.ZipFile. A loop is used to iterate through the files in the list, and zip.write() is used to add each file to the zip archive.

You can also add files to a specific directory within the zip archive by specifying the directory name in the arcname parameter of zip.write(). For example:

import zipfile
my_files = ['file1.txt', 'file2.txt', 'file3.txt']
my_dir = 'my_directory'
with zipfile.ZipFile('my_files.zip', 'w') as zip:
  for file in my_files:
    zip.write(file, arcname=my_dir+'/'+file)

This example creates a zip archive named my_files.zip with a directory named my_directory inside. Each file in my_files is added to this directory within the zip archive.

To create a tar file using Python

To create a tar file using Python, you can use the built-in tarfile module. Here’s an example of how to create a tar file with a list of files:

import tarfile
my_files = ['file1.txt', 'file2.txt', 'file3.txt']
with tarfile.open('my_files.tar', mode='w') as tar:
  for file in my_files:
    tar.add(file)

In this example, a list of files is defined in my_files, and a new tar file is created with tarfile.open(). A loop is used to iterate through the files in the list, and tar.add() is used to add each file to the tar archive.

You can also specify the compression of the tar file by passing the appropriate mode to tarfile.open(). For example, to create a gzipped tar file, you can use the w:gz mode like this:

import tarfile
my_files = ['file1.txt', 'file2.txt', 'file3.txt']
with tarfile.open('my_files.tar.gz', mode='w:gz') as tar:
  for file in my_files:
    tar.add(file)

This example creates a gzipped tar archive named my_files.tar.gz.

.

related content