Computer >> Máy Tính >  >> Lập trình >> Python

Làm việc với các tệp zip bằng Python

Trong Thư viện chuẩn của Python, có một mô-đun được gọi là zipfile. Sử dụng mô-đun này, chúng tôi 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ữ. Các tệp zip được sử dụng để có được các tính năng nén dữ liệu ít bị mất hơn, vì vậy từ dạng nén, nó có thể được tái tạo lại một cách hoàn hảo. Tệp zip có thể chứa một hoặc nhiều tệp nén trong đó.

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 truyền tốc độ qua các kết nối tiêu chuẩn.

Trong Python, chúng ta cần nhập mô-đun tệp zip để sử dụng tệp zip.

from zipfile import ZipFile

Đầu 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, lúc đầu, chúng ta phải thu thập dữ liệu toàn bộ thư mục để lấy tất cả các tệp và thư mục và lưu trữ các đường dẫn dưới dạng danh sách. Sau đó, mở tệp Zip dưới dạng chế độ ghi và ghi tất cả từ các đường dẫn được lưu trữ.

Mã mẫu

#Get all files from directory and subdirectories and convert to zip
from zipfile import ZipFile
import os
defget_all_files(directory): #function to get all files from directory
   paths = []
   for root, dirs, files in os.walk(directory):
      for f_name in files:
         path = os.path.join(root, f_name) #get a file and add the total path
         paths.append(path)
      return paths #Return the file paths
directory = './sample_files'
paths = get_all_files(directory)
#Display the filenames
print('The following files will be stored in the zip file')
for file in paths:
   print(file)
#Open zip file as write mode to create 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ờ, hãy xem cách giải nén các tệp zip bằng mô-đun zipfile. Để giải nén một tệp zip, trước tiên, chúng tôi phải mở tệp zip dưới dạng đọc 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 () lấy một đường dẫn để xác định vị trí tệp từ tệp Zip để giải nén.

Mã mẫu

#Extract the zip files
from zipfile import ZipFile
zip_file = 'my_files.zip'
with ZipFile(zip_file, 'r') as zf:
   #display the files inside the zip
   zf.printdir()
   #Extracting the files from zip file
   zf.extractall()
   print('Zip Extraction Completed')

Đầu ra

File Name Modified Sizesample_files/TP_python_prev.pdf 2018-10-19 13:19:48 1915882sample_files/text_files/file1.txt 2018-11-06 13:34:46 22sample_files/text_files/file2.txt 2018-11-06 13:35:02 24Zip Extraction Completed

Bây giờ, chúng ta sẽ thảo luận về phương thức infolist () của mô-đun 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ã mẫu

#Get information about the zip file
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 for 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): 1915882File Name: sample_files/text_files/file1.txt Modify Date: 2018-11-06 13:34:46 Zip Version: 20 System Version: 0 File Size (Bytes): 22File 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