How to Manage ZIP Files in Python

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

ZIP files are a popular file format for storing data because they compress well and can be handled by any computer system. In Python, you use the zipfile module to handle ZIP files on your behalf.

The “zipfile python” is a Python library that provides support for reading and writing ZIP files. The following are the steps to use the zipfile python.

How to Manage ZIP Files in Python

Zip files are useful for compressing data and are utilized in a variety of situations. You’re in luck if you’re writing a Python script and need to generate or decompress ZIP files.

You’ll learn how to zip and unzip (decompress) zip files using Python in this article.

Let’s get this party started!

Prerequisites

If you want to follow along with this lesson, you’ll need the following items:

How to Use Python Wget to Download Files

Using Python to Make a Zip File

Let’s get started by looking at how to zip files using Python. This lesson will start with the most basic way and go through numerous strategies.

To compress a single file, follow these steps:

1. Launch your preferred text editor.

2. Create a directory at /pythonzipdemo and download these BMP files into it if you want to follow along with the lesson precisely. All black.bmp, all blue.bmp, all green.bmp, and all red.bmp are the four bitmap files you should have after that. You’ll also get a demo.py Python script with all the code from this lesson.

The instructional files are bitmap images that benefit substantially from compression. Not all sorts of files can be compressed in the same way.

3. Name your new Python script demo.py. The sample script will be saved in the home directory or /demo.py in this tutorial.

4. Begin coding in your Python script. Import the zipfile module first. The zipfile module is a Python module that includes all of the methods you’ll need to zip and unzip files.

import zipfile # this imports the zipfile module, allowing you to utilize it.

5. Finally, use the ZipFile() method to create a zipfile object, open it in write mode (w), add a file to it, and finally shut the instance (close()).

## Create the single zip.zip archive with a new zipfile object. zf = zipfile.ZipFile(‘single file.zip’, mode=’w’) ## zf.write(‘all black.bmp’) ## Add a file to the archive ## zf.close zf.close zf.close zf.close zf.close zf.close zf.close ()

Relative routes are used in this lesson. The relative path searches for files in the current directory, which is where Python is operating. When giving file names, absolute paths may be used instead.

You should now see a file named single file.zip in the folder after running the script. Congrats! You’ve successfully zipped your first file! But hold on a second. It’s worth noting that it hasn’t shrunk in size. The zip file is not compressed by default. One additional step is required to compress the files within.

You may also use the with statement since zipfile is a context manager, e.g.

zipfile.write(‘all black.bmp’) with ZipFile(‘single file.zip’, ‘w’) as zipfile

6. Finally, while instantiating the zipfile object, provide a compression argument. The ZIP STORED, ZIP DEFLATED, ZIP BZIP2, and ZIP LZMA compression properties are used by the zipfile module to control how Python compresses the data within. That property is set to ZIP STORED by default, which means no compression.

You must use the ZIP DEFLATED property to compress the files within the archive, as demonstrated below.

zipfile import ## Create the single zip.zip archive and compress it with a new zipfile object zf = zipfile.ZipFile(‘single file.zip’, mode=’w’, compression=zipfile.ZIP DEFLATED) ## Add a file to the archive with zf.write(‘all black.bmp’) ## Close the archive with zf.release(‘all black.bmp’) ## Release the archive from memory with zf.release(‘all black.bmp’) close()

When you execute this script, the single file.zip file should now be significantly smaller than the real bitmap file.

Filters to Use When Zipping Files

A lot has previously been said about compressing files, but only by referring to the files manually. Specifying each file individually when dealing with a huge number of files is far from optimal.

You may use filters to filter the files you wish to work on. For example, a filter may be based on the file size or name.

Filtering files being added to a zip file isn’t possible since there aren’t any built-in options. You’ll have to come up with your own answer. Creating a Python function is one approach to construct your own solution. A Python function is a collection of code that may be run as a single unit. Using a function to “encapsulate” code into a single unit is a fantastic method to save time.

Python Functions for Newbies is related to Getting Started: Python Functions for Newbies.

There will be about four steps to the function to create for this task:

  1. In write mode, open the zip file.
  2. Read all of the files in the source folder from which you want to add files to the zip file.
  3. Iterate over each file to determine whether it matches a certain string.
  4. Add the file to the zip file if it matches the string.

This function is shown below. This function is more sophisticated than you may be used to, but it demonstrates Python’s versatility in enabling you to design anything you want.

In Python, a lambda is used to write short anonymous functions. Strings cannot be called, therefore lambda turns name to a function.

# This imports the zipfile module so that you may use it. # for manipulating folders import zipfile import os # to remove any prefix from a pathname file up to the final slash character from a particular directory that matches the criteria from os.path. basename import # def filter and zip files (destination file, source foulder, filter): def filter and zip files (destination file, source foulder, filter): as new zip using zipfile.ZipFile(destination file, mode=”w”, compression=zipfile.ZIP DEFLATED): # Walk through all of the files in the folder test = os.walk(source foulder) for folder, subfolders, and filenames in os.walk(source foulder): for filename in filenames: If filter(filename) is true, file path = os.path.join # generate entire filepath of file in directory (folder, filename) # Write new zip.write(file path, basename(file path)) to a zip file. # using filters filter and zip files(“only b colors.zip”, “.”, lambda name: name.startswith(“all b”)) to zip only colors that start with b to only b colors list zip file contents(“only b colors.zip”)

Counting the Number of Files in a Zip File

You can use Python to read the files within a zip file after you’ve produced it. Use the namelist() function to do this. The namelist() function returns an array of file names that may be used to query all files in a zip file.

Invoke the namelist() method on the zipfile object as shown below, building on the previous example.

zipfile import zip read = zipfile.ZipFile(‘single file.zip’, mode=’r’) ## Read the zip file zip read = zipfile.ZipFile(‘single file.zip’, mode=’r’) ## Examine the contents of zip read.namelist and single file.zip () ## Zip read.close closes the archive, freeing it from memory ()

Namelist() produces an array of each file in the zip file, as you can see. The zip file currently contains just one file (all black.bmp).

namelist() produces an array containing the names of all the files in the zip file. namelist() produces an array containing the names of all the files in the zip file.

Use a Python for loop to read each file name and insert a tab in the middle of each one, as seen below, for a more human-readable output of file names.

zipfile import ## To read a zip file, use zip read = zipfile. ‘single file.zip’, mode=’r’, ZipFile(‘single file.zip’, mode=’r’) ## Examine the contents of single file.zip files for file name: zip read.namelist() # prints the names of the files contained therein, with a tab for easier reading. zip read.close print(“t”, file name) ## Close the archive, freeing it from memory ()

Adding Files to a Zip File that Already Exists

So you’ve got a zip file already and want to add additional files to it. It’s no issue! All you have to do now is alter the mode in which you open the zip file.

To append a file to an existing zip file, open it in append mode (mode=’a’), then use the write() function with the file to append, as illustrated below.

zipfile import ## To add zip file = zipfile, open the zip file. ZipFile(‘single file.zip’, mode=’a’) ## Optionally inspect the contents of the zip file before using zip read. namelist() ## Include the file in the zip file. write(‘all blue.bmp’) ## Optionally, look at the files in the zip before using zip read. namelist() ## Release the archive from memory zip read by closing it. close()

Using the zipfile Module to Extract the Contents of Zip Files

Let’s move on to extracting files from zip files that already exist. You may do this by using the extract() and extractall() functions.

The next example opens the zip file for reading (mode=’r’) and then extracts a single file (all blue.bmp) to your home folder. It also shows how to extract all files from a zip file to your home folder using the extractall() function.

zipfile import ## Read zip file = zipfile by opening the zip file. ‘single file.zip’, mode=’r’, ZipFile(‘single file.zip’, mode=’r’) ## Extract a single file from the zip file to the zip file directory in your home directory. ## Extract all files from the zip file to your home directory zip file with extract(‘all blue.bmp’, path=”). extractall(‘path=’~’) ## Zip read closes the archive, freeing it from memory. close()

Using the shutil module to extract the contents of zip files

You may alternatively use shutil, which is a built-in Python module, as an alternative to the zipfile module. shutil is a general-purpose file management module that isn’t focused on zip files. It just so happens to provide several useful zip file ways.

To use the shutil module to extract the contents of zip files, provide the zip file and the location to which all files should be extracted. Shutil’s unpack archive() function, unlike the zipfile module’s extract() method, does not let you to choose files from the archive to extract.

import shutil ## imports the shutil module All of the files in the single zip.zip file should be extracted to your home folder. shutil.unpack archive(‘single file.zip’, “) shutil.unpack archive(‘single file.zip’, “) shutil.unpack archive(

Filters to Use When Unzipping Files

Let’s use the same process (forming a function) to unzip files that meet a given filter, as we did in the zip filtering section. The function example is shown below. This function reads a zip file, reads all files within the zip file, iterates over each file, and sends it to the extract() method if it meets the provided criteria.

zipfile import # def unzip filtered files (source file, destination folder, filter): unzip only files inside the zip file that match the filter using a zipfile As a source, use ZipFile(source file, “r”): source.namelist = list of file names () # In list of file names, you’ll obtain an iterable object for file name: # if filter(file name): if filter(file name): if filter(file name): if filter(file name): if filter(file_ # Extract the files to the source destination folder. unzip filtered files(“multiple files.zip”, “not b colors”, lambda name: not name.startswith(“all b”)) extract(file name,path=destination folder)

The results of performing the article's final function The results of performing the article’s final function

Conclusion

Working with zip files in Python should now be second nature to you. You should now be able to handle any zip file job that comes your way using the zipfile and shutil modules, as well as several Python methods.

How will you use what you’ve learned so far to your next Python project?

The “python read zip file without extracting” is a common problem in Python. In this tutorial, you will learn how to use the “zipfile” module in order to read a ZIP file and extract its contents.

Frequently Asked Questions

Can Python access zip files?

How do I extract a ZIP file in Python?

A: You can use the following function to extract a ZIP file in Python.
def unzip(filename, zipfile): with open(filename) as myZipFile: for iFileName in enumerate(zipfile): print(Extracting + filename + .txt) myZipFile = open(extracted_data/+iFilename, w) with zipfile.open(+filename,r) as zf:\ do: dataToBeExcludedFromOmit=zf.readline() if not dataToBeExcludedFromOmit==:myZipFile.write (dataToBeExcludedFromOmit) else :print(Couldnt find + filename ) # Extracts the contents of a .ZIP file pausing when it is done

How do I read a zip folder in Python?

A: To read a zip folder in Python, you first need to create the file object. The contents of the zip are then stored within it.

Related Tags

  • python create zip file from directory
  • zipfile python example
  • read zip file python
  • python create zip file from list of files
  • python create zip file in memory