Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách nén file với module ZIPFILE trong Python

Vấn đề

Bạn muốn tạo file nén (compressed) trong Python.

Giới thiệu

File ZIP chứa nội dung nén của nhiều file khác. Nén file giảm dung lượng trên đĩa, hữu ích khi truyền qua mạng (internet, Control-M AFT, Connect Direct, scp...).

Python tạo file ZIP với module zipfile.

Cách thực hiện

1. Chuẩn bị: Import module


import zipfile
import io
import pandas as pd

2. Hàm ghi dữ liệu ra file CSV


def write_data_to_files(inp_data, file_name):
    """ Ghi dữ liệu chuỗi vào file. """
    print(f" *** Writing the data to - {file_name}")
    throwaway_storage = io.StringIO(inp_data)
    with open(file_name, 'w') as f:
        for line in throwaway_storage:
            f.write(line)

3. Hàm nén file


def file_compress(inp_file_names, out_zip_file):
    """ Nén danh sách file vào file ZIP. """
    compression = zipfile.ZIP_DEFLATED  # Chế độ nén
    print(f" *** Input files: {inp_file_names}")
    print(f' *** Output zip: {out_zip_file}')
    
    zf = zipfile.ZipFile(out_zip_file, mode="w")
    try:
        for file_to_write in inp_file_names:
            print(f' *** Processing file {file_to_write}')
            zf.write(file_to_write, file_to_write, compress_type=compression)
    except FileNotFoundError as e:
        print(f' *** Exception: {e}')
    finally:
        zf.close()  # Quan trọng: phải close!

Giải thích:

  • Mở ZipFile với mode 'w' (ghi).
  • write(): tham số 1 = đường dẫn file nguồn, tham số 2 = tên bên trong archive, compress_type = thuật toán nén.
  • ZIP_DEFLATED: nén thực sự. ZIP_STORED: chỉ lưu không nén.
  • Luôn close() trong khối finally.

4. Chương trình chính: Tạo 2 file CSV và nén


if __name__ == '__main__':
    file_name1 = "temporary_file1_for_zip.csv"
    file_name2 = "temporary_file2_for_zip.csv"
    file_name_list = [file_name1, file_name2]
    zip_file_name = "temporary.zip"
    
    # Dữ liệu file 1: cầu thủ > 1 Grand Slam
    file_data_1 = """player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3"""
    
    # Dữ liệu file 2: cầu thủ ≤ 1 Grand Slam
    file_data_2 = """player,titles
Theim,1
Zverev,0
Medvedev,0
Rublev,0"""
    
    write_data_to_files(file_data_1, file_name1)
    write_data_to_files(file_data_2, file_name2)
    file_compress(file_name_list, zip_file_name)

Kết quả:

  • temporary_file1_for_zip.csv tạo tại thư mục hiện tại.
  • temporary_file2_for_zip.csv tạo tại thư mục hiện tại.
  • temporary.zip chứa 2 file nén.