Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีบีบอัดไฟล์ด้วยโมดูล ZIPFILE ใน Python

ปัญหา

ต้องการสร้างไฟล์บีบอัด (compressed files) ใน Python

บทนำ

ไฟล์ ZIP เก็บเนื้อหาที่บีบอัดของหลายไฟล์ การบีบอัดลดขนาดบนดิสก์ เหมาะสำหรับถ่ายโอนผ่านอินเทอร์เน็ตหรือระหว่างระบบ Python ใช้โมดูล zipfile สร้างไฟล์ ZIP

ขั้นตอนการทำงาน

1. เตรียมแพ็กเกจ: zipfile และ io

2. ฟังก์ชันเขียนข้อมูลตัวอย่างลงไฟล์


import io

def write_data_to_files(inp_data, file_name):
    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. ฟังก์ชันบีบอัดไฟล์ (zip)


import zipfile

def file_compress(inp_file_names, out_zip_file):
    compression = zipfile.ZIP_DEFLATED  # หรือ ZIP_STORED (เก็บแค่ไม่บีบอัด)
    print(f" *** Input File name passed for zipping - {inp_file_names}")
    print(f' *** out_zip_file is - {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 occurred during zip process - {e}')
    finally:
        zf.close()  # สำคัญ: ต้อง close ไฟล์ ZIP

ZipFile.write() อาร์กิวเมนต์แรก: path ไฟล์จริง, อาร์กิวเมนต์ที่สอง: ชื่อไฟล์ภายใน ZIP, compress_type: อัลกอริทึมบีบอัด

4. ตัวอย่างรันเต็ม: สร้าง 2 CSV แล้ว zip รวม


import zipfile
import io
import pandas as pd

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"

file_data_1 = """player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3"""

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)

ผลลัพธ์

  • temporary_file1_for_zip.csv สร้างใน current directory
  • temporary_file2_for_zip.csv สร้างใน current directory
  • temporary.zip สร้างใน current directory (มีทั้ง 2 ไฟล์ข้างใน)

สรุป

  • ใช้ zipfile.ZipFile(mode='w') สร้าง ZIP ใหม่
  • ใช้ ZIP_DEFLATED บีบอัดจริง, ZIP_STORED แค่เก็บไฟล์
  • ต้อง close() ZIP file เสมอ (หรือใช้ with statement)
  • จับ exception FileNotFoundError ป้องกันไฟล์หาย