Mastering ZIP File Handling in Python: Reading and Creating Zip Archives

max24816

Max

Posted on September 9, 2023

Mastering ZIP File Handling in Python: Reading and Creating Zip Archives

Python zipfile module is your go to tool for file compression. We'll explore how to read and create ZIP archives in Python, unlocking the power of file management and data compression.

Reading ZIP Files

Import the zipfile Module

To get started, import the zipfile module:

import zipfile
Enter fullscreen mode Exit fullscreen mode

Open and Extract from a ZIP File

Let's say we have a ZIP file named 'example.zip,' and we want to extract its contents. We can achieve this using the following code:

with zipfile.ZipFile('example.zip', 'r') as zip_ref:
    zip_ref.extractall('destination_folder')
Enter fullscreen mode Exit fullscreen mode
  • We use a context manager with the 'with' statement to open the ZIP file in read ('r') mode.
  • The 'extractall' method extracts all files and directories from the ZIP archive to the specified 'destination_folder.'

Reading Specific Files

To read the contents of specific files within the ZIP archive, you can iterate through the list of file names:

with zipfile.ZipFile('example.zip', 'r') as myzip:
    for file_name in myzip.namelist():
        with myzip.open(file_name) as myfile:
            content = myfile.read()
            print(f"File name: {file_name}")
            print(f"Content: {content.decode('utf-8')}")
Enter fullscreen mode Exit fullscreen mode
  • We iterate through the list of file names in the ZIP archive using 'namelist.'
  • For each file, we use 'open' to access its contents and read them.

Creating ZIP Files

Create a New ZIP File

Now, let's explore how to create a new ZIP file and add files to it. First, import the 'zipfile' module:

import zipfile
Enter fullscreen mode Exit fullscreen mode

Adding Files to a ZIP Archive

Suppose we have two files, 'file1.txt' and 'file2.txt,' that we want to compress into a new ZIP archive named 'example.zip.'

with zipfile.ZipFile('example.zip', 'w') as zip_ref:
    zip_ref.write('file1.txt', arcname='folder1/file1.txt')
    zip_ref.write('file2.txt', arcname='folder2/file2.txt')
Enter fullscreen mode Exit fullscreen mode
  • We open a new ZIP file named 'example.zip' in write ('w') mode.
  • 'write' is used to add files to the archive. We specify 'arcname' to set the internal folder structure within the ZIP file.

Zip file can be used to compress file which makes it easy to handle, increases the storage, easy to transfer the file in network or in email. Suppose if you want to send multiple report using cron job from your backend, using zipfile module make its easy to send email attachment as a zip format.

💖 💪 🙅 🚩
max24816
Max

Posted on September 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related