Các tệp zip rất tốt để nén dữ liệu và được sử dụng trong nhiều trường hợp khác nhau. Nếu bạn đang xây dựng tập lệnh Python và cần tạo hoặc giải nén các tệp ZIP Python, thì bạn thật may mắn
Trong hướng dẫn này, bạn sẽ học cách nén và giải nén [giải nén] các tệp zip, tất cả đều bằng Python
Bắt đầu nào
điều kiện tiên quyết
Nếu bạn muốn làm theo hướng dẫn này, hãy chắc chắn rằng bạn có những thứ sau
- Trăn 3
- Một trình soạn thảo văn bản, như Mã VS
Có liên quan. Cách tải tệp xuống bằng Python Wget
Tạo tệp Zip bằng Python
Hãy bắt đầu và trước tiên hãy tập trung vào việc nén tệp bằng Python. Hướng dẫn này sẽ bắt đầu bằng phương pháp đơn giản nhất có thể và sẽ dựa trên các kỹ thuật khác nhau
Để nén một tập tin duy nhất
1. Mở trình soạn thảo văn bản yêu thích của bạn
2. Nếu bạn muốn làm theo chính xác hướng dẫn, hãy tạo một thư mục tại ~/pythonzipdemo và tải các tệp BMP này vào đó. Sau khi thực hiện, bạn sẽ có bốn tệp bitmap; . bmp, all_blue. bmp, all_green. bmp và all_red. bmp. Bạn cũng sẽ có một bản demo. py Tập lệnh Python chứa tất cả mã trong hướng dẫn này
Các tệp hướng dẫn là các tệp bitmap, được hưởng lợi rất nhiều từ việc nén. Không phải tất cả các loại tệp cũng sẽ nén
3. Tạo tập lệnh Python mới có tên demo. py. Hướng dẫn này sẽ lưu tập lệnh demo trong thư mục chính hoặc ~/demo. py
4. Trong tập lệnh Python của bạn, hãy bắt đầu viết mã. Đầu tiên, nhập mô-đun
## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0. Mô-đun ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0 là mô-đun Python tích hợp có chứa tất cả các chức năng bạn cần để nén và giải nén tệp bằng Pythonimport zipfile # imports the zipfile module so you can make use of it
5. Tiếp theo, khởi tạo một đối tượng
## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0 bằng cách sử dụng phương thức ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
3, mở tệp zip ở chế độ ghi [## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
4], thêm một tệp vào đó, rồi đóng đối tượng [## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
5]## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
Hướng dẫn này dựa trên các đường dẫn tương đối. Đường dẫn tương đối tìm kiếm các tệp trong thư mục hiện tại, nơi Python hiện đang chạy. Thay vào đó, bạn có thể chỉ định đường dẫn tuyệt đối khi chỉ định tên tệp
Khi bạn chạy tập lệnh, bây giờ bạn sẽ thấy một tệp có tên là single_file. nén trong thư mục. chúc mừng. Bạn đã nén tệp đầu tiên của mình. Nhưng đợi đã. Lưu ý rằng nó không nhỏ hơn. Theo mặc định, tệp zip không được nén. Để nén các file bên trong, bạn phải thực hiện thêm một bước nữa
Vì
0 là trình quản lý bối cảnh, bạn cũng có thể sử dụng câu lệnh## Instantiate a new zipfile object creating the single_zip.zip archive. zf = zipfile.ZipFile['single_file.zip', mode='w'] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
7 e. g## Instantiate a new zipfile object creating the single_zip.zip archive. zf = zipfile.ZipFile['single_file.zip', mode='w'] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
8## Instantiate a new zipfile object creating the single_zip.zip archive. zf = zipfile.ZipFile['single_file.zip', mode='w'] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
9## Instantiate a new zipfile object creating the single_zip.zip archive. zf = zipfile.ZipFile['single_file.zip', mode='w'] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
6. Cuối cùng, thêm một tham số
import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0 khi khởi tạo đối tượng ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0. Mô-đun ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0 sử dụng các thuộc tính nén khác nhau như ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 và ZIP_LZMA chỉ ra cách Python nén các tệp bên trong. Theo mặc định, thuộc tính đó được đặt thành import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
3, nghĩa là không nénĐể nén các tệp bên trong kho lưu trữ, bạn phải chỉ định , như hình bên dưới
import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
Khi bạn chạy tập lệnh này, bây giờ bạn sẽ thấy rằng single_file. zip nhỏ hơn nhiều so với tệp bitmap thực tế
Áp dụng bộ lọc khi nén tệp
Rất nhiều về việc nén các tệp đã được đề cập, nhưng chỉ bằng cách tham khảo các tệp theo cách thủ công. Khi bạn phải xử lý một số lượng lớn tệp, việc chỉ định từng tệp theo cách thủ công là không lý tưởng
Bạn có thể lọc các tệp bạn muốn hoạt động dựa trên các bộ lọc. Ví dụ: bộ lọc có thể dựa trên kích thước tệp hoặc tên tệp
Không có cách tích hợp nào để lọc tệp được thêm vào tệp zip. Bạn sẽ cần xây dựng giải pháp của riêng mình. Một cách để xây dựng giải pháp của riêng bạn là tạo một hàm Python. Hàm Python là một bộ mã bạn có thể thực thi như một. Xây dựng một chức năng là một cách tuyệt vời để “đóng gói” code thành một đơn vị duy nhất
Có liên quan. Bắt đầu. Hàm Python cho người mới
Chức năng để xây dựng cho nhiệm vụ này sẽ bao gồm khoảng bốn giai đoạn riêng biệt
- Mở tệp zip ở chế độ ghi
- Đọc tất cả các tệp trong thư mục nguồn mà bạn muốn thêm tệp vào tệp zip từ đó
- Lặp lại từng tệp và kiểm tra xem nó có khớp với một chuỗi cụ thể không
- Nếu tệp khớp với chuỗi, hãy thêm nó vào tệp zip
Bạn có thể xem chức năng này bên dưới. Chức năng này phức tạp hơn những gì bạn có thể quen dùng nhưng nó cho thấy Python linh hoạt như thế nào, cho phép bạn tạo bất cứ thứ gì bạn cần
Một
5 trong Python được sử dụng để tạo các hàm ẩn danh nhỏ. Các chuỗi không thể gọi được và để làm choimport zipfile ## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
6 có thể gọi được;import zipfile ## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED] ## Add a file to the archive zf.write['all_black.bmp'] ## Close the archive releasing it from memory zf.close[]
# imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
Liệt kê nội dung của tệp Zip
Khi bạn đã tạo tệp zip, bạn cũng có thể sử dụng Python để đọc các tệp bên trong. Để làm điều đó, hãy sử dụng phương pháp
import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
9. Phương thức import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
9 là một cách thuận tiện để truy vấn tất cả các tệp trong tệp zip được trả về dưới dạng một mảng tên tệpNhư được hiển thị bên dưới, xây dựng từ ví dụ trước, gọi phương thức
import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
9 trên đối tượng ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
Bạn sẽ thấy rằng
import zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
9 trả về một mảng của mỗi tệp trong tệp zip. Tại thời điểm này, bạn sẽ chỉ thấy một tệp [all_black. bmp] trong tệp nénimport zipfile
## Instantiate a new zipfile object creating the single_zip.zip archive and compressing it
zf = zipfile.ZipFile['single_file.zip', mode='w', compression=zipfile.ZIP_DEFLATED]
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
9 trả về một mảng của từng tệp trong tệp zipNếu bạn muốn đầu ra tên tệp dễ đọc hơn với con người, hãy sử dụng vòng lặp Python để đọc từng tên tệp và đặt một tab ở giữa mỗi tên, như được hiển thị bên dưới
import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
files = zip_read.namelist[]
for file_name in files:
# prints the name of files within, with a tab for better readability
print["\t", file_name]
## Close the archive releasing it from memory
zip_read.close[]
Thêm tệp vào tệp Zip hiện có
Vì vậy, bạn đã có một tệp zip và muốn thêm một số tệp vào đó. Không vấn đề gì. Bạn chỉ cần thay đổi chế độ mà bạn mở tệp zip trong
Để thêm tệp vào tệp zip hiện có, hãy mở tệp zip ở chế độ chắp thêm [
# imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
5], sau đó gọi phương thức # imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
6 truyền tệp để thêm vào tệp zip, như minh họa bên dướiimport zipfile
## Open the zip file for appending
zip_file = zipfile.ZipFile['single_file.zip', mode='a']
## Optionally see the files in the zip before the addition
zip_read.namelist[]
## Add the file to the zip
zip_file.write['all_blue.bmp']
## Optionally see the files in the zip before after the addition
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
Trích xuất nội dung của tệp Zip bằng Mô-đun ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0
## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
Hãy chuyển sang giải nén tệp từ các tệp zip hiện có. Bằng cách sử dụng các phương pháp
# imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
8 và # imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
9, bạn có thể biến nó thành hiện thựcVí dụ dưới đây đang mở zip để đọc [
import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
0] sau đó giải nén một tệp duy nhất [import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
1] từ zip vào thư mục nhà của bạn. Nó cũng minh họa việc sử dụng phương pháp # imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
9 để giải nén tất cả các tệp trong zip vào thư mục chính của bạnimport zipfile
## Open the zip file for reading
zip_file = zipfile.ZipFile['single_file.zip', mode='r']
## Extract a single file from the zip file to your home directory
zip_file.extract['all_blue.bmp', path='~']
## Extract all files from the zip file to your home directory
zip_file.extractall['path='~']
## Close the archive releasing it from memory
zip_read.close[]
Trích xuất nội dung của tệp Zip Python bằng mô-đun import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
3
import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
Để thay thế cho việc sử dụng mô-đun
## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0, bạn cũng có thể sử dụng một mô-đun Python tích hợp khác có tên là import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
5. import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
3 là một mô-đun không tập trung cụ thể vào các tệp zip mà quản lý tệp tổng quát hơn. Tình cờ là có một số phương pháp tệp zip tiện dụng để sử dụngĐể trích xuất nội dung của các tệp zip bằng mô-đun
import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
3, hãy cung cấp tệp zip và đường dẫn để giải nén tất cả các tệp vào. Không giống như phương pháp # imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
8 trên mô-đun ## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0, phương pháp import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
files = zip_read.namelist[]
for file_name in files:
# prints the name of files within, with a tab for better readability
print["\t", file_name]
## Close the archive releasing it from memory
zip_read.close[]
0 của import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
3 không cho phép bạn chọn tệp từ kho lưu trữ để giải nén# imports the shutil module
import shutil
## Extract all files in the single_zip.zip file to your home folder.
shutil.unpack_archive['single_file.zip', '~']
Áp dụng bộ lọc khi giải nén tệp
Như đã trình bày trong phần lọc zip, giờ hãy áp dụng phương pháp tương tự [tạo hàm] để giải nén các tệp khớp với một bộ lọc cụ thể. Bạn có thể xem ví dụ chức năng bên dưới. Hàm này đọc một tệp zip, đọc tất cả các tệp bên trong tệp zip, lặp lại từng tệp và nếu tệp đó khớp với bộ lọc đã xác định, nó sẽ chuyển tệp đó sang phương thức
# imports the zipfile module so you can make use of it
import zipfile
# for manipulating directories
import os
# for deleting any prefix up to the last slash character of a pathname file from a given directory that matches the filter
from os.path import basename
# zip the files from given directory that matches the filter
def filter_and_zip_files [destination_file, source_foulder, filter]:
with zipfile.ZipFile[destination_file, mode="w", compression=zipfile.ZIP_DEFLATED] as new_zip:
# Iterate over all the files in the folder
test = os.walk[source_foulder]
for folder, subfolders, filenames in os.walk[source_foulder]:
for filename in filenames:
if filter[filename]:
# create complete filepath of file in directory
file_path = os.path.join[folder, filename]
# Add file to zip
new_zip.write[file_path, basename[file_path]]
# zipping only colors that start with b to only_b_colors by using_filters
filter_and_zip_files["only_b_colors.zip", ".", lambda name : name.startswith["all_b"]]
list_zip_file_contents["only_b_colors.zip"]
8import zipfile
# unzip only files withtin the zip file that match the filter
def unzip_filtered_files [source_file, destination_folder, filter]:
with zipfile.ZipFile[source_file, "r"] as source:
list_of_file_names = source.namelist[] # you'll get an iterable object
for file_name in list_of_file_names:
# checks if the file matches the filter
if filter[file_name]:
# Extract the files to destination_folder
source.extract[file_name,path=destination_folder]
unzip_filtered_files["multiple_files.zip", "not_b_colors", lambda name : not name.startswith["all_b"]]
Phần kết luận
Bây giờ bạn đã hiểu rõ về cách làm việc với các tệp zip trong Python. Sử dụng cả mô-đun
## Instantiate a new zipfile object creating the single_zip.zip archive.
zf = zipfile.ZipFile['single_file.zip', mode='w']
## Add a file to the archive
zf.write['all_black.bmp']
## Close the archive releasing it from memory
zf.close[]
0 và import zipfile
## Open the zip file for reading
zip_read = zipfile.ZipFile['single_file.zip', mode='r']
## Inspect the contents of single_file.zip
zip_read.namelist[]
## Close the archive releasing it from memory
zip_read.close[]
3, cùng với việc xây dựng một số hàm Python, giờ đây bạn sẽ biết cách quản lý bất kỳ tác vụ tệp zip nào được ném vào bạnBạn sẽ tích hợp kiến thức mới này vào dự án Python tiếp theo của mình như thế nào?
Ghét quảng cáo?
Khám phá sách hướng dẫn ATAThông tin khác từ ATA Learning & Partners
Tài nguyên được đề xuất
Tài nguyên được đề xuất cho đào tạo, bảo mật thông tin, tự động hóa, v.v.
Được trả tiền để viết
ATA Learning luôn tìm kiếm những người hướng dẫn ở mọi cấp độ kinh nghiệm. Bất kể bạn là quản trị viên cấp dưới hay kiến trúc sư hệ thống, bạn đều có điều gì đó để chia sẻ. Tại sao không viết trên một nền tảng có khán giả hiện có và chia sẻ kiến thức của bạn với mọi người?
Sách hướng dẫn học tập ATA
ATA Learning được biết đến với các hướng dẫn bằng văn bản chất lượng cao dưới dạng các bài đăng trên blog. Hỗ trợ Học tập ATA với sách điện tử PDF Sách hướng dẫn ATA khả dụng ngoại tuyến và không có quảng cáo
Làm cách nào để giải nén zip bằng Python?
Python3. # vào một địa điểm cụ thể. Nhập mô-đun zipfile Tạo đối tượng tệp zip bằng lớp ZipFile. Gọi phương thức extract[] trên đối tượng tệp zip và chuyển tên của tệp cần giải nén và đường dẫn nơi tệp cần được giải nén và Giải nén tệp cụ thể có trong zip< . .Làm cách nào để cài đặt tệp zip trong Python?
Để biết thêm thông tin, hãy xem Python Setuptools. .Tải xuống tệp zip pynrfjprogGiải nén tệp zip đã nén và mở cửa sổ Dấu nhắc Lệnh trong thư mục đóNhập thiết lập python. py cài đặt tại Dấu nhắc Lệnh. Nội dung của gói sẽ được thêm vào thư mục mặc định của PythonTệp zip trong Python ở đâu?
Trong mô-đun tệp zip, bạn sẽ tìm thấy lớp ZipFile . Lớp này hoạt động khá giống với hàm open[] tích hợp sẵn của Python, cho phép bạn mở các tệp ZIP của mình bằng các chế độ khác nhau. Chế độ đọc [ "r"] là mặc định.