Examples
Python ZIP Archives
Handling ZIP Archives
Python ZIP archives create and extract files with zipfile.
Introduction to Python zipfile Module
The zipfile
module in Python provides tools to create, read, write, append, and list a ZIP file. This module is part of the standard library, so you don't need to install anything extra to use it. ZIP files are used to compress multiple files into a single file that takes up less space and is easy to transfer.
Creating a ZIP Archive
To create a ZIP archive, you can open a new file in write mode using the zipfile.ZipFile
class. The following example demonstrates how to create a ZIP archive and add files to it:
Extracting Files from a ZIP Archive
To extract files from a ZIP archive, you can use the extractall()
method. This method will extract all files to the specified directory. Below is an example of how to extract files from a ZIP archive:
Listing Contents of a ZIP Archive
You can also list the contents of a ZIP archive without extracting them. This can be done using the namelist()
method, as shown in the example below:
Adding Files to an Existing ZIP Archive
If you want to add files to an existing ZIP archive, open the file in append mode ('a'
). Here's how you can do it:
Handling ZIP Archive Passwords
While the zipfile
module supports reading protected ZIPs, it does not support writing them. You can extract files from a password-protected ZIP archive by providing the password to the extractall()
or extract()
method. Here's how to do it:
Examples
- Previous
- Statistics Calc
- Next
- Threaded Tasks