By Python Coding

Published: 2025-03-06

URL: https://pythonclcoding.substack.com/p/create-a-zip-file-using-python


Code Explanation:

import zipfile

  • This imports the built-in zipfile module, which allows us to create, read, write, and manipulate ZIP files.

files = ['file1.txt', 'file2.txt']

  • This is a list containing the names of files (file1.txt, file2.txt) that we want to include in the ZIP archive.

# Create a ZIP file with zipfile.ZipFile('pycl.zip', 'w') as zipf:

  • zipfile.ZipFile('pycl.zip', 'w'): This creates a new ZIP file named pycl.zip in write mode ('w').
  • The with statement ensures that the ZIP file is properly closed after execution.

for file in files: zipf.write(file)

  • This loops through the files list and adds each file to the ZIP archive using zipf.write(file).
  • If file1.txt and file2.txt exist in the current directory, they will be added to pycl.zip.

print("ZIP file created!")

  • This prints a confirmation message after successfully creating the ZIP file.

What This Code Does:

✅ Creates a ZIP file named pycl.zip. ✅ Adds file1.txt and file2.txt to the ZIP file. ✅ Ensures the ZIP file is properly closed after writing.


Example Output:

ZIP file created!