Trong Thư viện chuẩn của Python, có một module gọi là zipfile. Sử dụng module này, chúng ta có thể thực hiện các thao tác khác nhau trên tệp zip.
Tệp Zip là định dạng tệp lưu trữ. Tệp zip được dùng để có tính năng nén dữ liệu không mất mát, vì vậy từ dạng nén, nó có thể được tái tạo hoàn hảo. Một tệp zip có thể chứa một hoặc nhiều tệp nén trong nó.
Các tính năng tốt của tệp zip là: nó giảm yêu cầu lưu trữ, và cũng tăng tốc độ truyền qua các kết nối tiêu chuẩn.
Trong Python chúng ta cần nhập module zipfile để sử dụng tệp zip.
from zipfile import ZipFile
Trước tiên chúng ta sẽ xem cách tạo tệp Zip từ một thư mục. Trong trường hợp này, thư mục chính chứa một tệp và một số thư mục khác.
Vì vậy trước tiên, chúng ta phải duyệt toàn bộ thư mục để lấy tất cả tệp và thư mục và lưu trữ các đường dẫn như một danh sách. Sau đó mở tệp Zip ở chế độ ghi, và ghi tất cả từ các đường dẫn đã lưu.
Mã ví dụ
# Lấy tất cả tệp từ thư mục và thư mục con và chuyển thành zip
from zipfile import ZipFile
import os
def get_all_files(directory):
# hàm lấy tất cả tệp từ thư mục
paths = []
for root, dirs, files in os.walk(directory):
for f_name in files:
path = os.path.join(root, f_name) # lấy tệp và thêm tổng đường dẫn
paths.append(path)
return paths # Trả về đường dẫn tệp
directory = './sample_files'
paths = get_all_files(directory)
# Hiển thị tên tệp
print('The following files will be stored in the zip file')
for file in paths:
print(file)
# Mở tệp zip ở chế độ ghi để tạo zip
with ZipFile('my_files.zip', 'w') as zf:
for file in paths:
zf.write(file)
print('Zip is created Successfully')
Đầu ra
The following files will be stored in the zip file ./sample_files\TP_python_prev.pdf ./sample_files\text_files\file1.txt ./sample_files\text_files\file2.txt Zip is Created Successfully
Bây giờ xem, cách giải nén tệp zip sử dụng module zipfile. Để giải nén một zip, trước tiên, chúng ta phải mở tệp zip ở chế độ read, và sau đó sử dụng phương thức extract() hoặc extractall() để trích xuất nội dung. Phương thức extract() nhận một đường dẫn để định vị tệp từ tệp Zip để trích xuất.
Mã ví dụ
# Giải nén tệp zip
from zipfile import ZipFile
zip_file = 'my_files.zip'
with ZipFile(zip_file, 'r') as zf:
# hiển thị các tệp bên trong zip
zf.printdir()
# Trích xuất các tệp từ tệp zip
zf.extractall()
print('Zip Extraction Completed')
Đầu ra
File Name Modified Size sample_files/TP_python_prev.pdf 2018-10-19 13:19:48 1915882 sample_files/text_files/file1.txt 2018-11-06 13:34:46 22 sample_files/text_files/file2.txt 2018-11-06 13:35:02 24 Zip Extraction Completed
Bây giờ, chúng ta sẽ thảo luận về phương thức infolist() của module zipfile. Điều này cung cấp danh sách các thông tin khác nhau như tên tệp, ngày sửa đổi, Kích thước tệp, v.v.
Mã ví dụ
# Lấy thông tin về tệp zip
from zipfile import ZipFile
import datetime
zip_file = 'my_files.zip'
with ZipFile(zip_file, 'r') as zf:
for detail in zf.infolist():
print('File Name: ' + detail.filename)
print('\tModify Date: ' + str(datetime.datetime(*detail.date_time)))
print('\tZip Version: ' + str(detail.create_version))
print('\tSystem Version: ' + str(detail.create_system)) # 0 cho windows
print('\tFile Size (Bytes): ' + str(detail.file_size))
Đầu ra
File Name: sample_files/TP_python_prev.pdf Modify Date: 2018-10-19 13:19:48 Zip Version: 20 System Version: 0 File Size (Bytes): 1915882 File Name: sample_files/text_files/file1.txt Modify Date: 2018-11-06 13:34:46 Zip Version: 20 System Version: 0 File Size (Bytes): 22 File Name: sample_files/text_files/file2.txt Modify Date: 2018-11-06 13:35:02 Zip Version: 20 System Version: 0 File Size (Bytes): 24