Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Zip File and Directory

In this tutorial, you'll learn how to work with ZIP files in Python using the zipfile module, which allows you to create, read, and extract ZIP files.

  • Creating a ZIP file:

To create a new ZIP file, you can use the ZipFile class from the zipfile module. Here's an example of how to create a ZIP file containing one file:

import zipfile

# Create a new ZIP file
with zipfile.ZipFile('path/to/your/archive.zip', mode='w') as archive:
    # Add a file to the archive
    archive.write('path/to/your/file.txt', arcname='file.txt')

To add multiple files or directories, use a loop:

import zipfile
import os

files_to_zip = ['file1.txt', 'file2.txt', 'path/to/directory']

with zipfile.ZipFile('path/to/your/archive.zip', mode='w') as archive:
    for file_path in files_to_zip:
        arcname = os.path.basename(file_path)
        archive.write(file_path, arcname=arcname)
  • Reading a ZIP file:

To read the contents of a ZIP file, you can use the ZipFile class and its methods, such as namelist() and getinfo():

import zipfile

with zipfile.ZipFile('path/to/your/archive.zip', mode='r') as archive:
    # Get the list of files in the archive
    file_names = archive.namelist()

    # Print the list of files
    for name in file_names:
        print(name)

        # Get file info and print file size
        file_info = archive.getinfo(name)
        print(f"Size: {file_info.file_size} bytes")
  • Extracting a ZIP file:

To extract the contents of a ZIP file, you can use the extractall() or extract() methods of the ZipFile class:

import zipfile

with zipfile.ZipFile('path/to/your/archive.zip', mode='r') as archive:
    # Extract all files to the specified directory
    archive.extractall('path/to/your/destination')

To extract a single file from the ZIP archive:

import zipfile

with zipfile.ZipFile('path/to/your/archive.zip', mode='r') as archive:
    # Extract a single file to the specified directory
    archive.extract('file.txt', 'path/to/your/destination')
  • Compressing files with different compression levels:

By default, the ZipFile class uses the ZIP_STORED compression method, which means the files are stored without any compression. To compress files, you can use the ZIP_DEFLATED method, which requires the zlib library:

import zipfile
import os

files_to_zip = ['file1.txt', 'file2.txt']
compression_level = zipfile.ZIP_DEFLATED

with zipfile.ZipFile('path/to/your/archive.zip', mode='w') as archive:
    for file_path in files_to_zip:
        arcname = os.path.basename(file_path)
        archive.write(file_path, arcname=arcname, compress_type=compression_level)

In this example, the files in the ZIP archive will be compressed using the ZIP_DEFLATED method, which uses the Deflate algorithm for compression.

  1. Create zip file in Python:

    • Description: Use the zipfile module to create a zip file.
    • Code:
      import zipfile
      
      zip_file_path = 'example.zip'
      
      with zipfile.ZipFile(zip_file_path, 'w') as zip_file:
          zip_file.write('file1.txt')
          zip_file.write('file2.txt')
      
  2. Zip and unzip files in Python:

    • Description: Zip and unzip files using the zipfile module.
    • Code:
      import zipfile
      
      # Zip files
      with zipfile.ZipFile('example.zip', 'w') as zip_file:
          zip_file.write('file1.txt')
          zip_file.write('file2.txt')
      
      # Unzip files
      with zipfile.ZipFile('example.zip', 'r') as zip_file:
          zip_file.extractall('extracted_files')
      
  3. Compress and decompress files in Python:

    • Description: Compress and decompress files using the gzip module.
    • Code:
      import gzip
      import shutil
      
      # Compress file
      with open('file.txt', 'rb') as file:
          with gzip.open('file.txt.gz', 'wb') as gzip_file:
              shutil.copyfileobj(file, gzip_file)
      
      # Decompress file
      with gzip.open('file.txt.gz', 'rb') as gzip_file:
          with open('decompressed_file.txt', 'wb') as file:
              shutil.copyfileobj(gzip_file, file)
      
  4. Zip a directory in Python:

    • Description: Use shutil.make_archive to zip a directory.
    • Code:
      import shutil
      
      shutil.make_archive('example_directory', 'zip', 'directory_to_zip')
      
  5. Python shutil.make_archive() example:

    • Description: Use shutil.make_archive for zipping and archiving.
    • Code:
      import shutil
      
      shutil.make_archive('archive', 'zip', 'source_directory')
      
  6. Extract files from a zip archive in Python:

    • Description: Use zipfile to extract files from a zip archive.
    • Code:
      import zipfile
      
      with zipfile.ZipFile('example.zip', 'r') as zip_file:
          zip_file.extract('file1.txt', 'destination_folder')
      
  7. Python zipfile.extractall() method:

    • Description: Use extractall() to extract all files from a zip archive.
    • Code:
      import zipfile
      
      with zipfile.ZipFile('example.zip', 'r') as zip_file:
          zip_file.extractall('destination_folder')
      
  8. Add files to an existing zip archive in Python:

    • Description: Add files to an existing zip archive using zipfile.
    • Code:
      import zipfile
      
      with zipfile.ZipFile('existing_archive.zip', 'a') as zip_file:
          zip_file.write('new_file.txt')
      
  9. Python zip directory and subdirectories:

    • Description: Zip a directory with its subdirectories using shutil.make_archive.
    • Code:
      import shutil
      
      shutil.make_archive('example_directory', 'zip', 'directory_to_zip')
      
  10. Recursive zip and unzip in Python:

    • Description: Recursively zip and unzip directories.
    • Code:
      import shutil
      
      # Recursive zip
      shutil.make_archive('example_directory', 'zip', 'directory_to_zip')
      
      # Recursive unzip
      shutil.unpack_archive('example_directory.zip', 'extracted_directory')
      
  11. Password-protected zip files in Python:

    • Description: Create a password-protected zip file using zipfile.
    • Code:
      import zipfile
      
      with zipfile.ZipFile('password_protected.zip', 'w', zipfile.ZIP_DEFLATED) as zip_file:
          zip_file.setpassword(b'my_password')
          zip_file.write('file1.txt')
          zip_file.write('file2.txt')
      
  12. Working with zip file comments in Python:

    • Description: Add and read comments in a zip file.
    • Code:
      import zipfile
      
      # Add comment to a zip file
      with zipfile.ZipFile('example.zip', 'w') as zip_file:
          zip_file.comment = b'This is a comment'
          zip_file.write('file1.txt')
      
      # Read comment from a zip file
      with zipfile.ZipFile('example.zip', 'r') as zip_file:
          comment = zip_file.comment
          print(f'Comment: {comment.decode("utf-8")}')
      
  13. Create a self-extracting zip file in Python:

    • Description: Create a self-extracting zip file using shutil.make_archive.
    • Code:
      import shutil
      
      shutil.make_archive('self_extracting', 'zip', 'source_directory')
      
  14. Splitting and joining large zip files in Python:

    • Description: Split and join large zip files.
    • Code:
      import shutil
      
      # Split large zip file
      shutil.split('large_file.zip', 'split_zip', 1000000)
      
      # Join split zip files
      shutil.join('split_zip', 'large_file_reconstructed.zip')
      
  15. Check if a file is a zip file in Python:

    • Description: Check if a file is a zip file using zipfile.
    • Code:
      import zipfile
      
      is_zip = zipfile.is_zipfile('example.zip')
      print(f'Is a zip file: {is_zip}')
      
  16. Extract specific files from a zip archive in Python:

    • Description: Extract specific files from a zip archive.
    • Code:
      import zipfile
      
      with zipfile.ZipFile('example.zip', 'r') as zip_file:
          files_to_extract = ['file1.txt', 'file2.txt']
          for file in files_to_extract:
              zip_file.extract(file, 'destination_folder')
      
  17. Error handling when working with zip files in Python:

    • Description: Implement error handling when working with zip files.
    • Code:
      import zipfile
      
      try:
          # Try to create a zip file
          with zipfile.ZipFile('example.zip', 'w') as zip_file:
              zip_file.write('file1.txt')
              zip_file.write('file2.txt')
      except Exception as e:
          print(f'Error: {e}')