Trong nhiều trường hợp, bạn sẽ gặp các tệp nén [hoặc cần phải tự nén tệp]. Vì các tệp zip rất phổ biến nên có thể làm việc với chúng theo lập trình là một kỹ năng quan trọng. Trong hướng dẫn này, bạn sẽ học cách nén và giải nén tệp bằng Python
Đến cuối hướng dẫn này, bạn sẽ học được
- Cách nén tệp bằng Python
- Cách thêm tệp vào tệp zip hiện có
- Cách nén tệp bằng mật khẩu bảo vệ [mã hóa]
- Cách giải nén một tệp, một số tệp hoặc tất cả các tệp trong tệp zip
- Cách giải nén tệp có điều kiện
Mục lục
Hiểu mô-đun zipfile Python
Python đi kèm với một mô-đun, zipfile, để tạo, đọc, viết và nối thêm vào tệp zip. Vì mô-đun được tích hợp sẵn trong Python nên không cần cài đặt bất cứ thứ gì. Đặc biệt, mô-đun zipfile đi kèm với một lớp, ZipFile
, có nhiều phương thức hữu ích để cho phép bạn đọc và ghi các tệp zip trong Python
Trước tiên, hãy đi sâu vào sử dụng mô-đun để tìm hiểu cách nén tệp bằng mô-đun zipfile
Cách nén tệp bằng Python
Để nén tệp bằng Python, chúng ta có thể tạo tệp zip bằng lớp Zipfile. Khi chúng ta mở Tệp Zip lần đầu tiên, Python sẽ tạo tệp nếu nó chưa tồn tại. Vì điều này, chúng ta có thể chỉ cần gọi hành động
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
0 mà không cần tạo tệp trướcTừ đó, chúng ta có thể sử dụng phương pháp
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
1 để thêm các tệp riêng lẻ vào tệp zip. Để làm cho quá trình này dễ dàng hơn, chúng ta có thể sử dụng vòng lặp for để chuyển nhiều tệp trong một hành động. Nếu chúng ta muốn thêm tất cả các tệp vào một thư mục, chúng ta có thể tạo danh sách tất cả các tệp trong một thư mụcHãy xem cách chúng ta có thể sử dụng Python để nén tệp, sử dụng tất cả các tệp trong một thư mục
# How to Zip All Files in a Directory
import os
import zipfile
directory = '/Users/datagy/files'
files = os.listdir[directory]
with zipfile.ZipFile['zipfile.zip', 'w'] as zip:
for file in files:
file_path = os.path.join[directory, file]
zip.write[file_path]
Trong ví dụ trên, chúng tôi đã sử dụng hàm
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
2 để liệt kê tất cả các tệp trong một thư mục. Sau đó, chúng tôi đã sử dụng trình quản lý ngữ cảnh # Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
3 để mở tệp. Lợi ích của việc này là Python sẽ tự động đóng tệp khi mọi thao tác được thực hiện xongTừ đó, chúng tôi lặp lại danh sách các tệp và ghi từng tệp vào tệp zip bằng phương pháp
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
1Cách thêm tệp vào tệp Zip hiện có trong Python
Việc thêm tệp vào tệp zip thú vị được thực hiện dễ dàng bằng cách sử dụng lớp Zipfile. Khi bạn khởi tạo một đối tượng Zipfile, bạn có thể mở nó ở chế độ chắp thêm bằng cách sử dụng chế độ
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
5. Từ đó, quy trình hoạt động giống như khi bạn thêm tệp vào tệp mới tạoHãy xem cách chúng ta có thể sử dụng lớp Zipfile để thêm tệp vào tệp zip hiện có
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
Lưu ý rằng trong khối mã ở trên, chúng tôi sử dụng đối số thứ hai,
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
6. Hãy cùng xem sự khác biệt giữa hai thông số này
7 đại diện cho tệp mà bạn muốn thêm vào tệp zip của mình# Add a File to An Existing Zip File in Python import os import zipfile directory = '/Users/datagy/old/' file_name = 'file.txt' with zipfile.ZipFile['zipfile.zip', 'a'] as zip: file_path = os.path.join[directory, file_name] zip.write[filename=file_path, arcname=file_name]
6 đại diện cho đường dẫn và tên tệp bạn muốn sử dụng trong kho lưu trữ# Add a File to An Existing Zip File in Python import os import zipfile directory = '/Users/datagy/old/' file_name = 'file.txt' with zipfile.ZipFile['zipfile.zip', 'a'] as zip: file_path = os.path.join[directory, file_name] zip.write[filename=file_path, arcname=file_name]
Nếu chúng ta để trống đối số thứ hai, thì nó sẽ sử dụng giá trị tên tệp. Điều này sẽ sao chép toàn bộ cấu trúc thư mục, nghĩa là trong trường hợp của chúng ta, Python sẽ thêm thư mục
# Add a File to An Existing Zip File in Python
import os
import zipfile
directory = '/Users/datagy/old/'
file_name = 'file.txt'
with zipfile.ZipFile['zipfile.zip', 'a'] as zip:
file_path = os.path.join[directory, file_name]
zip.write[filename=file_path, arcname=file_name]
9Cách giải nén tệp Zip bằng Python
Để giải nén tệp zip bằng Python, bạn có thể sử dụng phương thức
# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
0 và sử dụng tùy chọn # Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
1 để đọc tệp. Điều này chỉ đơn giản là mở tệp ở chế độ đọc. Tuy nhiên, làm thế nào chúng ta có thể nhìn thấy những gì bên trong nó?Đó là nơi mà phương pháp
# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
2 phát huy tác dụng. Phương thức sẽ in ra nội dung và một số thông tin về nội dung. Hãy xem cái này trông như thế nào# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
Bây giờ chúng tôi có thể thấy rằng tệp zip của chúng tôi có bốn tệp khác nhau
Cách trích xuất một tệp từ tệp Zipfile bằng Python
Để giải nén một tập tin, chúng ta có thể sử dụng phương thức
# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
3. Phương thức lấy cả tên tệp mà bạn muốn giải nén và thư mục đíchHãy xem xét kỹ hơn về phương pháp chi tiết hơn
# Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
Chúng ta có thể thấy rằng phương thức có ba tham số khác nhau. Hãy chia nhỏ những điều này chi tiết hơn
4 là tệp bạn muốn giải nén# Printing Contents of a Zip File import zipfile with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip: zip.printdir[] # Returns: # File Name Modified Size # file1.txt 2022-11-13 12:51:02 0 # file2.txt 2022-11-13 07:22:26 0 # file3.txt 2022-11-13 07:22:46 0 # file4.txt 2022-11-13 07:22:46 0
5 là đích đến của nơi bạn muốn đặt tệp# Printing Contents of a Zip File import zipfile with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip: zip.printdir[] # Returns: # File Name Modified Size # file1.txt 2022-11-13 12:51:02 0 # file2.txt 2022-11-13 07:22:26 0 # file3.txt 2022-11-13 07:22:46 0 # file4.txt 2022-11-13 07:22:46 0
6 là mật khẩu nếu tệp được mã hóa [chúng tôi sẽ sớm đề cập đến]# Printing Contents of a Zip File import zipfile with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip: zip.printdir[] # Returns: # File Name Modified Size # file1.txt 2022-11-13 12:51:02 0 # file2.txt 2022-11-13 07:22:26 0 # file3.txt 2022-11-13 07:22:46 0 # file4.txt 2022-11-13 07:22:46 0
Hãy xem nó trông như thế nào để trích xuất một tệp từ tệp zip trong Python
# How to Extract a File from a Zip File in Python
import zipfile
with zipfile.ZipFile['/Users/datagy/Archive.zip', 'r'] as zip:
zip.extract['file1.txt', '/Users/datagy/']
Lưu ý rằng chúng tôi đang mở tệp zip bằng phương pháp
# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
1, cho biết chúng tôi muốn đọc tệp. Sau đó, chúng tôi hướng dẫn Python trích xuất # Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
8 và đặt nó vào thư mục # Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
9Trong nhiều trường hợp, bạn sẽ muốn trích xuất nhiều hơn một tệp. Trong phần sau, bạn sẽ tìm hiểu cách giải nén tất cả các tệp từ tệp zip bằng Python
Cách trích xuất tất cả các tệp từ tệp Zipfile bằng Python
Để trích xuất tất cả các tệp từ một tệp zip trong Python, bạn có thể sử dụng phương thức
# Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
0. Phương pháp này chỉ yêu cầu bạn chuyển vào đường dẫn đích đến nơi bạn muốn trích xuất tất cả các thành viên của tệp zipHãy xem cách trích xuất tất cả các tệp từ tệp zip trong Python
# How to Extract All Files from a Zip File in Python
import zipfile
with zipfile.ZipFile['/Users/datagy/Archive.zip', 'r'] as zip:
zip.extractall['/Users/datagy/all/']
Trong ví dụ trên, chúng ta có thể thấy việc trích xuất tất cả các tệp từ tệp zip đơn giản như thế nào. Trước tiên, chúng tôi mở tệp zip bằng trình quản lý ngữ cảnh. Từ đó, chúng tôi chỉ cần chuyển đường dẫn của nơi chúng tôi muốn giải nén các tệp vào phương thức
# Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
0Trong phần tiếp theo, bạn sẽ tìm hiểu cách giải mã các tệp được mã hóa
Cách giải mã tệp Zip được bảo vệ bằng mật khẩu bằng Python
Thư viện zipfile Python cho phép bạn dễ dàng giải mã các tệp zip có mật khẩu. Khi bạn đang làm việc với một tệp được bảo vệ bằng mật khẩu và chỉ cần cố gắng lấy một tệp, Python sẽ tăng
# Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
2. Hãy xem nó trông như thế nàoimport zipfile
with zipfile.ZipFile['/Users/datagy/password.zip', 'r'] as zip:
zip.extractall['/Users/datagy/all/']
# Returns:
# RuntimeError: File is encrypted, password required for extraction
Hãy xem cách chúng tôi có thể nhập mật khẩu để giải nén các tệp từ tệp zip được bảo vệ bằng mật khẩu. Các phương thức
# Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
0 và # Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
3 đều chấp nhận một tham số bổ sung, # Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
6. Tham số này chấp nhận mật khẩu của tệp zip hoặc của chính tệp riêng lẻHãy xem cách chúng ta có thể sử dụng Python để trích xuất tệp từ tệp được bảo vệ bằng mật khẩu
# How to Extract Files from a Password Protected Zip File
import zipfile
with zipfile.ZipFile['/Users/datagy/password.zip', 'r'] as zip:
zip.extractall['/Users/datagy/all/', pwd=b'datagy']
Trong ví dụ trên, chúng tôi chuyển mật khẩu vào tham số
# Printing Contents of a Zip File
import zipfile
with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip:
zip.printdir[]
# Returns:
# File Name Modified Size
# file1.txt 2022-11-13 12:51:02 0
# file2.txt 2022-11-13 07:22:26 0
# file3.txt 2022-11-13 07:22:46 0
# file4.txt 2022-11-13 07:22:46 0
6. Lưu ý rằng chúng tôi đang sử dụng một chuỗi nhị phân, như đã lưu ý bằng cách đặt tiền tố một # Understanding the .extract[] Method
ZipFile.extract[member, path=None, pwd=None]
7 trước chính chuỗi đóCách giải nén tệp có điều kiện bằng Python
Trong phần này, bạn sẽ tìm hiểu cách giải nén tệp có điều kiện. Điều này có thể hữu ích nếu bạn có một tệp zip lớn và chỉ muốn giải nén các tệp thuộc một loại tệp nhất định. Tương tự, bạn có thể sử dụng phương pháp mà bạn sẽ học để chỉ giải nén các tệp nhỏ hơn một kích thước tệp nhất định
Để giải nén file có điều kiện ta có thể loop từng file trong file zip xem có thỏa điều kiện không. Hãy xem cách chúng ta có thể sử dụng Python để chỉ trích xuất các tệp jpg từ tệp zip của mình
# How to Extract Files Conditionally
import zipfile
import os
with zipfile.ZipFile['/Users/datagy/Archive.zip', 'r'] as zip:
files = zip.namelist[]
for file in files:
filename, extension = os.path.splitext[file]
if extension == '.jpg':
zip.extract[file, '/Users/datagy/Conditionally/']
Hãy chia nhỏ cách giải nén tệp có điều kiện từ tệp zip trong Python
- Mở tệp zip bằng phương pháp đọc
- Sau đó, chúng tôi nhận được danh sách tất cả các tệp trong tệp zip bằng phương pháp
8# Understanding the .extract[] Method ZipFile.extract[member, path=None, pwd=None]
- Sau đó, chúng tôi lặp lại từng tệp và lấy tên tệp và phần mở rộng cho từng tệp để kiểm tra phần mở rộng của nó
- Nếu tiện ích mở rộng khớp với tiện ích mở rộng mong muốn, thì chúng tôi giải nén nó bằng phương pháp
3# Printing Contents of a Zip File import zipfile with zipfile.ZipFile['/Users/nikpi/ThatExcelSiteGSC/Archive.zip', 'r'] as zip: zip.printdir[] # Returns: # File Name Modified Size # file1.txt 2022-11-13 12:51:02 0 # file2.txt 2022-11-13 07:22:26 0 # file3.txt 2022-11-13 07:22:46 0 # file4.txt 2022-11-13 07:22:46 0
Phần kết luận
Trong hướng dẫn này, bạn đã học cách sử dụng Python để nén và giải nén tệp. Có thể làm việc với các tệp nén là một thực tế phổ biến bất kể bạn làm việc trong ngành nào. Ví dụ: làm việc trong lĩnh vực khoa học dữ liệu, bạn sẽ thường thấy các bản ghi giao dịch được nén để tiết kiệm dung lượng
Trước tiên, bạn đã học cách tạo tệp zip và cách thêm một tệp hoặc tất cả các tệp trong tệp zip. Từ đó, bạn đã học cách mở tệp zip và lấy một tệp hoặc tất cả các tệp. Sau đó, bạn đã học cách xử lý các tệp được bảo vệ bằng mật khẩu. Cuối cùng, bạn đã học cách giải nén tệp theo điều kiện, chẳng hạn như tệp thuộc một loại nhất định