Các kiểu nén zipfile python

Nối tiếp hướng dẫn lập trình Python, hôm nay chúng ta sẽ học cách tạo ra file zip bằng cách sử dụng Python, thông qua thư viện zipfile. Thư viện này được tích hợp sẵn trong Python 3 nên các bạn không nhất thiết phải thực hiện cài đặt

Create File Zip using Python

Đầu tiên là nhập thư viện filezip

import zipfile

Selection mode for zip file zip

# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except Exception as ex:
    compression = zipfile.ZIP_STORED
    print[ex]

Tạo tệp Zip với đường dẫn và chế độ [w – write, a – append]

# create the zip file first parameter path/name, second mode
zf = zipfile.ZipFile['vinasupport.com.zip', mode='w']

Thêm tệp vào tệp zip vừa tạo

# Add file to the zip file
# first parameter file to zip, second filename in zip
zf.write['vinasupport.com.txt', 'vinasupport.com.txt', compress_type=compression

Đóng tập tin

# Don't forget to close the file!
zf.close[]

Do đó đoạn mã đầy đủ sẽ là

import zipfile

# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except Exception as ex:
    compression = zipfile.ZIP_STORED
    print[ex]

# create the zip file first parameter path/name, second mode
zf = zipfile.ZipFile['vinasupport.com.zip', mode='w']

# Add file to the zip file
# first parameter file to zip, second filename in zip
zf.write['vinasupport.com.txt', 'vinasupport.com.txt', compress_type=compression]

# Don't forget to close the file!
zf.close[]

Kết quả

Sau khi chạy đoạn mã trên chúng tôi đã tạo thành công tệp zip

Đây là chương trình tạo file zip đơn giản, các bạn muốn làm nhiều thư mục hơn như thư mục zip, tạo mật khẩu cho file zip thì vui lòng tham khảo hướng dẫn sử dụng thư viện zipfile tại đây

Các tệp ZIP có thể chứa nội dung nén của nhiều tệp khác. Nén tệp làm giảm kích thước của tệp trên đĩa, điều này rất hữu ích khi truyền tệp qua internet hoặc giữa các hệ thống bằng Control-m AFT hoặc Connect direct hoặc thậm chí scp

Các chương trình Python tạo các tệp ZIP bằng các hàm trong mô-đun zipfile

Làm thế nào để làm nó

1. Chúng tôi sẽ sử dụng các gói zipfile và io. Cài đặt chúng với pip nếu bất kỳ gói nào bị thiếu trên hệ thống của bạn. Nếu bạn không chắc chắn, hãy sử dụng lệnh đóng băng pip để xác thực các gói

2. Chúng ta sẽ viết một hàm để ghi dữ liệu mẫu vào một tệp. Hàm write_data_to_files bên dưới lấy dữ liệu làm đầu vào và tạo một tệp trong tên thư mục hiện tại

Thí dụ

# Function : write_data_to_files
def write_data_to_files[inp_data, file_name]:
"""
function : create a csv file with the data passed to this code
args : inp_data : data to be written to the target file
file_name : target file name to store the data
return : none
assumption : File to be created and this code are in same directory.
"""
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. Bây giờ chúng ta sẽ viết một hàm file_compress để nén các tệp đã tạo ở bước trên. Chức năng này chấp nhận danh sách các tệp, duyệt qua chúng và nén nó thành tệp zip. Giải thích chi tiết của từng bước được cung cấp trong các ý kiến

Để tạo các tệp ZIP nén của riêng bạn, bạn phải mở đối tượng ZipFile ở chế độ ghi bằng cách chuyển 'w' làm đối số thứ hai

Khi bạn chuyển một đường dẫn tới phương thức write[] của đối tượng ZipFile, Python sẽ nén tệp tại đường dẫn đó và thêm nó vào tệp ZIP

Đối số đầu tiên cho phương thức write[] là một chuỗi tên tệp cần thêm

Đối số thứ hai là tham số kiểu nén - cho máy tính biết nên sử dụng thuật toán nào để nén tệp

Thí dụ

# Function : file_compress
def file_compress[inp_file_names, out_zip_file]:
"""
function : file_compress
args : inp_file_names : list of filenames to be zipped
out_zip_file : output zip file
return : none
assumption : Input file paths and this code is in same directory.
"""
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
compression = zipfile.ZIP_DEFLATED
print[f" *** Input File name passed for zipping - {inp_file_names}"]

# create the zip file first parameter path/name, second mode
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:
# Add file to the zip file
# first parameter file to zip, second filename in zip
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:
# Don't forget to close the file!
zf.close[]

4. Chúng tôi sẽ gọi các chức năng để tạo hai tệp csv và sau đó nén chúng. Chúng tôi sẽ sử dụng dữ liệu của các vận động viên quần vợt đã giành được hơn 1 danh hiệu Grand Slam vào một tệp - tệp tạm thời1 for_zip. csv và những người chơi quần vợt đã giành được ít hơn hoặc bằng 1 Grand Slam trong một tệp khác tệp tạm thời1 for_zip. csv. Sau đó, chúng tôi sẽ nén cả hai tệp này thành tệp tạm thời. tập tin nén

Chủ Đề