Use python to zip a file and directory

29/12/2020
A compressed file contains many files, directory and subdirectories. Many applications are available to create a compress file of any large file or directory and retrieve files or folders by extracting a compressed file. When we want to transfer any large or folder over the Internet then it is better to compress the content before transferring. This makes the task faster. You can use python scripts for compressing and extracting any large file or directory. zipfile module of python is used to do the task. How you can use python3 to compress any file or directory is shown in this tutorial by using various examples.

Example-1: Compressing a single file

Create a new file named ‘zipcode1.py’ and add the following code. zipfile module is imported to compress the file. temp.zip is assigned as zip file name with write mode and next, the original filename, temp.txt and compress type are given as parameters in the write method.

import zipfile
zip_file = zipfile.ZipFile(‘temp.zip’, ‘w’)
zip_file.write(‘temp.txt’, compress_type=zipfile.ZIP_DEFLATED)
zip_file.close()

Run the script

$ python3 zipcode1.py

The size of temp.txt is 27 bytes and after compression, the size of temp.zip is 2 bytes.

Example-2: Compressing a particular directory

Create a new file named ‘zipcode2.py’ and add the following code. A directory may contains many files, folders and subfolders. To read the content of the directory, os module of python is imported with zipfile module to compress the directory. In this script, mydir directory is used for compression.

# import required modules
 
import os
import zipfile
 
 
# Declare the function to return all file paths of the particular directory
def retrieve_file_paths(dirName):
 
  # setup file paths variable
  filePaths = []
   
  # Read all directory, subdirectories and file lists
  for root, directories, files in os.walk(dirName):
    for filename in files:
        # Create the full filepath by using os module.
        filePath = os.path.join(root, filename)
        filePaths.append(filePath)
         
  # return all paths
  return filePaths
 
 
# Declare the main function
def main():
# Assign the name of the directory to zip
  dir_name = ‘mydir’
   
  # Call the function to retrieve all files and folders of the assigned directory
  filePaths = retrieve_file_paths(dir_name)
   
  # printing the list of all files to be zipped
  print(‘The following list of files will be zipped:’)
  for fileName in filePaths:
    print(fileName)
     
  # writing files to a zipfile
  zip_file = zipfile.ZipFile(dir_name+‘.zip’, ‘w’)
  with zip_file:
    # writing each file one by one
    for file in filePaths:
      zip_file.write(file)
       
  print(dir_name+‘.zip file is created successfully!’)
   
# Call the main function
if __name__ == "__main__":
  main()

Run the script

$ python3 zipcode2.py

The size of mydir is 21 bytes and after compression, the size of mydir.zip is 2 bytes.

Example-3: Compressing a directory given by command line argument

Create a new file named ‘zipcode3.py’ and add the following code. To read the command line value, another python module sys is imported with os and zipfile modules.

# import required modules
 
import os
import sys
import zipfile
 
# Declare the function to return all file paths of a particular directory
def retrieve_file_paths(dirName):
 
  # setup file paths variable
  filePaths = []
   
  # Read all directory, subdirectories and file lists
  for root, directories, files in os.walk(dirName):
    for filename in files:
      # Create the full filepath by using os module.
      filePath = os.path.join(root, filename)
      filePaths.append(filePath)
       
  # return all paths
  return filePaths
 
 
# Declare the main function
def main():
 
  # Check two arguments are given at the time of running the script
  if len (sys.argv) != 2 :
    print ("You have enter the name of the directory to zip")
    sys.exit (1)
   
  # Set the directory name from command argument
  dir_name = sys.argv[1]
   
  # Set the zip file name
  zipFileName = dir_name + ".zip"
   
  # Call the function to retrieve all files and folders of the assigned directory
  filePaths = retrieve_file_paths(dir_name)
   
  # print the list of files to be zipped
  print(‘The following list of files will be zipped:’)
  for fileName in filePaths:
    print(fileName)
   
  # write files and folders to a zipfile
  zip_file = zipfile.ZipFile(zipFileName, ‘w’)
  with zip_file:
    # write each file seperately
    for file in filePaths:
      zip_file.write(file)
       
  print(zipFileName+‘ file is created successfully!’)
   
# Call the main function
if __name__ == "__main__":
  main()

Run the script

$ python3 zipcode3.py

test is given as directory name in the command line argument. The size of test is 21 bytes and after compression, the size of test.zip is 2 bytes.

I hope, this tutorial will help you to use python for compressing any file or directory.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

How to install and use Python(x,y) in Python

Python is a very popular programming language now for developing different types of applications or solving programming...
29/12/2020

Pandas read_csv Tutorial

Pandas .read_csv I have already discussed some of the history and uses for the Python library pandas.  pandas was designed...
28/12/2020

Python QR Code generator

What are QR codes? QR codes are some of the fastest-growing trends in today’s world when it comes to sharing any sort...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Reliable IPv4 and IPv6 Subnet Rental Services: The Perfect Solution for Global Businesses
23/12/2024

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024