Hướng dẫn python modify zip file - python sửa đổi tệp zip

Python cung cấp mô -đun zipfile để đọc và ghi các tệp zip. Bài viết trước của chúng tôi, ví dụ Python: Liệt kê các tệp trong kho lưu trữ ZIP và & nbsp; tải xuống và đọc tệp zip trong bộ nhớ bằng Python Hiển thị cách liệt kê và đọc các tệp bên trong tệp zip.

Show

Trong ví dụ này, chúng tôi sẽ chỉ ra cách sao chép các tệp từ tệp zip này sang tệp khác và sửa đổi một trong các tệp trong tiến trình. Đây thường là trường hợp nếu bạn muốn sử dụng các định dạng tệp zip như ODT hoặc LBX làm mẫu, thay thế các phần của nội dung văn bản của tệp.

import zipfile

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
    # Iterate the input files
    for inzipinfo in inzip.infolist():
        # Read input file
        with inzip.open(inzipinfo) as infile:
            if inzipinfo.filename == "test.txt":
                content = infile.read()
                # Modify the content of the file by replacing a string
                content = content.replace("abc", "123")
                # Write conte
                outzip.writestr(inzipinfo.filename, content)
            else: # Other file, dont want to modify => just copy it
                

Sau khi mở cả tệp đầu vào và zip đầu ra bằng cách sử dụng

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:

Chúng tôi lặp lại tất cả các tệp trong tệp ZIP đầu vào:

for inzipinfo in inzip.infolist():

Trong trường hợp chúng tôi đã gặp phải tệp mà chúng tôi muốn sửa đổi, được xác định bởi nó FileName & NBSP; ________ 48:

if inzipinfo.filename == "test.txt":

Chúng tôi đọc và sửa đổi nội dung.

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")

Voi và viết nội dung đã sửa đổi vào ZIP đầu ra:

outzip.writestr("test.txt", content)

Mặt khác, nếu tệp hiện tại không phải là tệp chúng tôi muốn sửa đổi, & nbsp; Chúng tôi chỉ sao chép tệp vào zip đầu ra bằng cách sử dụng

outzip.writestr(inzipinfo.filename, infile.read())

Lưu ý rằng thuật toán sẽ luôn luôn & nbsp; ________ 49 Tệp từ zip đầu vào, do đó toàn bộ nội dung của nó sẽ được lưu tạm thời trong bộ nhớ. Do đó, nó không hoạt động tốt cho các tệp lớn khi không nén.

Hướng dẫn python modify zip file - python sửa đổi tệp zip

Tạo các tệp zip của riêng bạn để lưu trữ và nén dữ liệu kỹ thuật số của bạn

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)

Bạn cũng đã học cách sử dụng

outzip.writestr("test.txt", content)
0 từ dòng lệnh của mình để liệt kê, tạo và trích xuất các tệp zip của bạn. Với kiến ​​thức này, bạn đã sẵn sàng lưu trữ, nén và thao tác hiệu quả dữ liệu kỹ thuật số của mình bằng định dạng tệp ZIP.

Cập nhật một tập tin trong một zip không được hỗ trợ. Bạn cần xây dựng lại một kho lưu trữ mới mà không cần tệp, sau đó thêm phiên bản cập nhật.

Python sườn

outzip.writestr("test.txt", content)
0 là một mô -đun thư viện tiêu chuẩn nhằm thao tác các tệp zip. Định dạng tệp này là một tiêu chuẩn công nghiệp được áp dụng rộng rãi khi nói đến việc lưu trữ và nén dữ liệu kỹ thuật số. Bạn có thể sử dụng nó để đóng gói một số tệp liên quan. Nó cũng cho phép bạn giảm kích thước tệp của mình và lưu không gian đĩa. Quan trọng nhất, nó tạo điều kiện trao đổi dữ liệu trên mạng máy tính.ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data. You can use it to package together several related files. It also allows you to reduce the size of your files and save disk space. Most importantly, it facilitates data exchange over computer networks.

Biết cách tạo, đọc, viết, điền, trích xuất và liệt kê các tệp zip bằng mô -đun

outzip.writestr("test.txt", content)
0 là một kỹ năng hữu ích để có nhà phát triển Python hoặc kỹ sư DevOps.

Trong hướng dẫn này, bạn sẽ học cách:

  • Đọc, ghi và trích xuất các tệp từ các tệp zip với Python từ
    outzip.writestr("test.txt", content)
    0
    files from ZIP files with Python’s
    outzip.writestr("test.txt", content)
    0
  • Đọc siêu dữ liệu về nội dung của các tệp zip bằng
    outzip.writestr("test.txt", content)
    0metadata about the content of ZIP files using
    outzip.writestr("test.txt", content)
    0
  • Sử dụng
    outzip.writestr("test.txt", content)
    0 để thao tác các tệp thành viên trong các tệp zip hiện cómanipulate member files in existing ZIP files
  • Tạo các tệp zip của riêng bạn để lưu trữ và nén dữ liệu kỹ thuật số của bạnnew ZIP files to archive and compress files

Bạn cũng đã học cách sử dụng

outzip.writestr("test.txt", content)
0 từ dòng lệnh của mình để liệt kê, tạo và trích xuất các tệp zip của bạn. Với kiến ​​thức này, bạn đã sẵn sàng lưu trữ, nén và thao tác hiệu quả dữ liệu kỹ thuật số của mình bằng định dạng tệp ZIP.

Python sườn

outzip.writestr("test.txt", content)
0 là một mô -đun thư viện tiêu chuẩn nhằm thao tác các tệp zip. Định dạng tệp này là một tiêu chuẩn công nghiệp được áp dụng rộng rãi khi nói đến việc lưu trữ và nén dữ liệu kỹ thuật số. Bạn có thể sử dụng nó để đóng gói một số tệp liên quan. Nó cũng cho phép bạn giảm kích thước tệp của mình và lưu không gian đĩa. Quan trọng nhất, nó tạo điều kiện trao đổi dữ liệu trên mạng máy tính.

Biết cách tạo, đọc, viết, điền, trích xuất và liệt kê các tệp zip bằng mô -đun

outzip.writestr("test.txt", content)
0 là một kỹ năng hữu ích để có nhà phát triển Python hoặc kỹ sư DevOps.

Trong hướng dẫn này, bạn sẽ học cách:

Đọc, ghi và trích xuất các tệp từ các tệp zip với Python từ

outzip.writestr("test.txt", content)
0 are a well-known and popular tool in today’s digital world. These files are fairly popular and widely used for cross-platform data exchange over computer networks, notably the Internet.

Đọc siêu dữ liệu về nội dung của các tệp zip bằng

outzip.writestr("test.txt", content)
0

Tạo các tệp zip mới để lưu trữ và nén các tệp

Nếu bạn thường xử lý các tệp zip, thì kiến ​​thức này có thể giúp hợp lý hóa quy trình công việc của bạn để xử lý các tệp của bạn một cách tự tin.Để tận dụng tối đa hướng dẫn này, bạn nên biết những điều cơ bản của việc làm việc với các tệp, sử dụng câu lệnh
outzip.writestr("test.txt", content)
5, xử lý các đường dẫn hệ thống tệp với
outzip.writestr("test.txt", content)
6 và làm việc với các lớp và lập trình hướng đối tượng.
Để có được các tệp và tài liệu lưu trữ mà bạn sẽ sử dụng để mã hóa các ví dụ trong hướng dẫn này, hãy nhấp vào liên kết bên dưới:Bắt đầu với các tệp zip
Các tệp ZIP là một công cụ nổi tiếng và phổ biến trong thế giới kỹ thuật số ngày nay. Các tệp này khá phổ biến và được sử dụng rộng rãi để trao đổi dữ liệu đa nền tảng trên mạng máy tính, đặc biệt là Internet.Bạn có thể sử dụng các tệp ZIP để kết hợp các tệp thông thường với nhau thành một kho lưu trữ, nén dữ liệu của bạn để lưu một số không gian đĩa, phân phối các sản phẩm kỹ thuật số của bạn và hơn thế nữa. Trong hướng dẫn này, bạn sẽ học cách thao tác các tệp ZIP bằng mô -đun PythonTHER
outzip.writestr("test.txt", content)
0.
Bởi vì các thuật ngữ xung quanh các tệp zip đôi khi có thể gây nhầm lẫn, hướng dẫn này sẽ tuân thủ các quy ước sau đây về thuật ngữ:Kỳ hạn

Nghĩa

Tệp zip, kho lưu trữ zip hoặc lưu trữ

Một tệp vật lý sử dụng định dạng tệp zipZIP archives, are files that use the ZIP file format.

Tập tin

Một tập tin máy tính thông thường

Tệp thành viên

Mặc dù có các định dạng lưu trữ tương tự khác, chẳng hạn như các tệp RAR và TAR, định dạng tệp ZIP đã nhanh chóng trở thành một tiêu chuẩn chung để lưu trữ dữ liệu hiệu quả và để trao đổi dữ liệu trên mạng máy tính.

Các tập tin zip ở khắp mọi nơi. Ví dụ, các bộ văn phòng như Microsoft Office và Libre Office dựa vào định dạng tệp ZIP làm tệp container tài liệu của họ. Điều này có nghĩa là

outzip.writestr("test.txt", content)
9,
outzip.writestr(inzipinfo.filename, infile.read())
0,
outzip.writestr(inzipinfo.filename, infile.read())
1,
outzip.writestr(inzipinfo.filename, infile.read())
2,
outzip.writestr(inzipinfo.filename, infile.read())
3,
outzip.writestr(inzipinfo.filename, infile.read())
4 thực sự là các tài liệu lưu trữ zip chứa một số tệp và thư mục tạo thành mỗi tài liệu. Các tệp phổ biến khác sử dụng định dạng ZIP bao gồm các tệp
outzip.writestr(inzipinfo.filename, infile.read())
5,
outzip.writestr(inzipinfo.filename, infile.read())
6 và
outzip.writestr(inzipinfo.filename, infile.read())
7.

Bạn có thể quen thuộc với GitHub, nơi cung cấp lưu trữ web để phát triển phần mềm và kiểm soát phiên bản bằng Git. GitHub sử dụng các tệp ZIP để đóng gói các dự án phần mềm khi bạn tải chúng xuống máy tính cục bộ của bạn. Ví dụ: bạn có thể tải xuống các giải pháp tập thể dục cho Python Basics: Giới thiệu thực tế về cuốn sách Python 3 trong tệp zip hoặc bạn có thể tải xuống bất kỳ dự án nào khác mà bạn chọn.

Các tệp ZIP cho phép bạn tổng hợp, nén và mã hóa các tệp thành một thùng chứa có thể tương tác và di động. Bạn có thể truyền phát các tệp ZIP, chia chúng thành các phân đoạn, làm cho chúng tự giải thoát và hơn thế nữa.

Tại sao sử dụng các tệp zip?

Biết cách tạo, đọc, viết và trích xuất các tệp zip có thể là một kỹ năng hữu ích cho các nhà phát triển và chuyên gia làm việc với máy tính và thông tin kỹ thuật số. Trong số các lợi ích khác, các tệp ZIP cho phép bạn:

  • Giảm kích thước của các tệp và yêu cầu lưu trữ của chúng mà không mất thông tin and their storage requirements without losing information
  • Cải thiện tốc độ truyền qua mạng do giảm kích thước và chuyển tệp đơn due to reduced size and single-file transfer
  • Đóng gói một số tệp liên quan lại với nhau thành một kho lưu trữ duy nhất để quản lý hiệu quả into a single archive for efficient management
  • Gói mã của bạn vào một kho lưu trữ duy nhất cho mục đích phân phối for distribution purposes
  • Bảo mật dữ liệu của bạn bằng cách sử dụng mã hóa, đây là một yêu cầu phổ biến hiện nay, which is a common requirement nowadays
  • Đảm bảo tính toàn vẹn của thông tin của bạn để tránh những thay đổi tình cờ và độc hại đối với dữ liệu của bạn to avoid accidental and malicious changes to your data

Các tính năng này làm cho các tệp zip trở thành một bổ sung hữu ích cho hộp công cụ Python của bạn nếu bạn đang tìm kiếm một cách linh hoạt, di động và đáng tin cậy để lưu trữ các tệp kỹ thuật số của bạn.

Python có thể thao túng các tệp zip không?

Đúng! Python có một số công cụ cho phép bạn thao tác các tệp zip. Một số công cụ này có sẵn trong thư viện tiêu chuẩn Python. Chúng bao gồm các thư viện cấp thấp để nén và giải nén dữ liệu bằng cách sử dụng các thuật toán nén cụ thể, chẳng hạn như

outzip.writestr(inzipinfo.filename, infile.read())
8,
outzip.writestr(inzipinfo.filename, infile.read())
9,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
0 và các thuật toán khác.

Python cũng cung cấp một mô-đun cấp cao có tên

outzip.writestr("test.txt", content)
0 được thiết kế cụ thể để tạo, đọc, ghi, trích xuất và liệt kê nội dung của các tệp zip. Trong hướng dẫn này, bạn sẽ tìm hiểu về Python từ
outzip.writestr("test.txt", content)
0 và cách sử dụng nó một cách hiệu quả.

Thao tác với các tệp zip hiện có với Python từ outzip.writestr("test.txt", content)0

Python sườn

outzip.writestr("test.txt", content)
0 cung cấp các lớp và chức năng thuận tiện cho phép bạn tạo, đọc, viết, trích xuất và liệt kê nội dung của các tệp zip của bạn. Dưới đây là một số tính năng bổ sung mà
outzip.writestr("test.txt", content)
0 hỗ trợ:

  • Các tệp ZIP lớn hơn 4 Gib (Tệp Zip64)
  • Giải mã dữ liệu
  • Một số thuật toán nén, chẳng hạn như xì hơi, BZIP2 và LZMA
  • Kiểm tra tính toàn vẹn thông tin với CRC32

Xin lưu ý rằng

outzip.writestr("test.txt", content)
0 có một vài hạn chế. Ví dụ, tính năng giải mã dữ liệu hiện tại có thể khá chậm vì nó sử dụng mã Python thuần túy. Mô -đun có thể xử lý việc tạo các tệp zip được mã hóa. Cuối cùng, việc sử dụng các tệp zip nhiều đĩa cũng không được hỗ trợ. Mặc dù những hạn chế này,
outzip.writestr("test.txt", content)
0 vẫn là một công cụ tuyệt vời và hữu ích. Hãy đọc để khám phá khả năng của nó.

Mở các tệp zip để đọc và viết

Trong mô -đun

outzip.writestr("test.txt", content)
0, bạn sẽ tìm thấy lớp
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Lớp này hoạt động khá giống với chức năng
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
0 tích hợp 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 (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
1) là mặc định. Bạn cũng có thể sử dụng các chế độ Write (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2), nối tiếp (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3) và độc quyền (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
4). Bạn sẽ tìm hiểu thêm về từng điều này trong một khoảnh khắc.

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 thực hiện giao thức Trình quản lý bối cảnh để bạn có thể sử dụng lớp trong câu lệnh
outzip.writestr("test.txt", content)
5. Tính năng này cho phép bạn nhanh chóng mở và làm việc với tệp zip mà không phải lo lắng về việc đóng tệp sau khi bạn hoàn thành công việc của mình.context manager protocol so that you can use the class in a
outzip.writestr("test.txt", content)
5 statement. This feature allows you to quickly open and work with a ZIP file without worrying about closing the file after you finish your work.

Trước khi viết bất kỳ mã nào, hãy đảm bảo bạn có một bản sao của các tệp và tài liệu lưu trữ mà bạn sẽ sử dụng:

Để chuẩn bị sẵn môi trường làm việc của bạn, hãy đặt các tài nguyên đã tải xuống vào một thư mục có tên

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
7 trong thư mục nhà của bạn. Khi bạn có các tệp ở đúng nơi, hãy chuyển sang thư mục mới được tạo và kích hoạt một phiên tương tác Python ở đó.

Để khởi động, bạn sẽ bắt đầu bằng cách đọc tệp zip có tên

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8. Để làm điều đó, bạn có thể sử dụng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 trong chế độ đọc:

>>>

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

Đối số đầu tiên cho trình khởi tạo của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể là một chuỗi đại diện cho đường dẫn đến tệp zip mà bạn cần mở. Đối số này cũng có thể chấp nhận các đối tượng giống như tệp và giống như đường dẫn. Trong ví dụ này, bạn sử dụng một đường dẫn dựa trên chuỗi.

Đối số thứ hai của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 là một chuỗi một chữ cái đại diện cho chế độ mà bạn sẽ sử dụng để mở tệp. Như bạn đã học ở đầu phần này,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể chấp nhận bốn chế độ có thể, tùy thuộc vào nhu cầu của bạn. Đối số vị trí
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
3 mặc định là
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
1, vì vậy bạn có thể thoát khỏi nó nếu bạn muốn mở kho lưu trữ chỉ để đọc.

Bên trong câu lệnh

outzip.writestr("test.txt", content)
5, bạn gọi
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6 vào
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
7. Biến
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
7 hiện đang giữ phiên bản của chính
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Chức năng này cung cấp một cách nhanh chóng để hiển thị nội dung của tệp zip bên dưới trên màn hình của bạn. Đầu ra của chức năng có định dạng bảng thân thiện với người dùng với ba cột thông tin:

  • with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
    00
  • with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
    01
  • with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
    02

Nếu bạn muốn đảm bảo rằng bạn đang nhắm mục tiêu một tệp zip hợp lệ trước khi bạn cố gắng mở nó, thì bạn có thể kết thúc

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 trong câu lệnh
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
04 ____ ____105 và bắt bất kỳ ngoại lệ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
06 nào:

>>>

>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file

Đối số đầu tiên cho trình khởi tạo của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể là một chuỗi đại diện cho đường dẫn đến tệp zip mà bạn cần mở. Đối số này cũng có thể chấp nhận các đối tượng giống như tệp và giống như đường dẫn. Trong ví dụ này, bạn sử dụng một đường dẫn dựa trên chuỗi.

Đối số thứ hai của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 là một chuỗi một chữ cái đại diện cho chế độ mà bạn sẽ sử dụng để mở tệp. Như bạn đã học ở đầu phần này,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể chấp nhận bốn chế độ có thể, tùy thuộc vào nhu cầu của bạn. Đối số vị trí
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
3 mặc định là
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
1, vì vậy bạn có thể thoát khỏi nó nếu bạn muốn mở kho lưu trữ chỉ để đọc.

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
0

Đối số đầu tiên cho trình khởi tạo của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể là một chuỗi đại diện cho đường dẫn đến tệp zip mà bạn cần mở. Đối số này cũng có thể chấp nhận các đối tượng giống như tệp và giống như đường dẫn. Trong ví dụ này, bạn sử dụng một đường dẫn dựa trên chuỗi.

Đối số thứ hai của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 là một chuỗi một chữ cái đại diện cho chế độ mà bạn sẽ sử dụng để mở tệp. Như bạn đã học ở đầu phần này,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 có thể chấp nhận bốn chế độ có thể, tùy thuộc vào nhu cầu của bạn. Đối số vị trí
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
3 mặc định là
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
1, vì vậy bạn có thể thoát khỏi nó nếu bạn muốn mở kho lưu trữ chỉ để đọc.

Bên trong câu lệnh

outzip.writestr("test.txt", content)
5, bạn gọi
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6 vào
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
7. Biến
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
7 hiện đang giữ phiên bản của chính
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Chức năng này cung cấp một cách nhanh chóng để hiển thị nội dung của tệp zip bên dưới trên màn hình của bạn. Đầu ra của chức năng có định dạng bảng thân thiện với người dùng với ba cột thông tin:

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
1

Nếu bạn muốn đảm bảo rằng bạn đang nhắm mục tiêu một tệp zip hợp lệ trước khi bạn cố gắng mở nó, thì bạn có thể kết thúc

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 trong câu lệnh
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
04 ____ ____105 và bắt bất kỳ ngoại lệ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
06 nào:

Ví dụ đầu tiên mở thành công

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 mà không cần tăng ngoại lệ ____106. Điều đó vì
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 có định dạng zip hợp lệ. Mặt khác, ví dụ thứ hai không thành công trong việc mở
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
10, vì tệp không phải là tệp zip hợp lệ.

Để kiểm tra tệp zip hợp lệ, bạn cũng có thể sử dụng chức năng

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
11:

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
2

Trong các ví dụ này, bạn sử dụng một câu lệnh có điều kiện với

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
11 làm điều kiện. Hàm này lấy đối số
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
13 giữ đường dẫn đến tệp zip trong hệ thống tệp của bạn. Đối số này có thể chấp nhận các đối tượng chuỗi, giống như tệp hoặc giống như đường dẫn. Hàm trả về
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
14 nếu
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
13 là tệp zip hợp lệ. Nếu không, nó trả về
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
16.

Bây giờ nói rằng bạn muốn thêm

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 vào kho lưu trữ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
18 bằng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Để làm điều đó, bạn có thể sử dụng chế độ ghi (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2). Chế độ này mở một tệp zip để viết. Nếu tệp zip đích tồn tại, thì chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2 cắt ngắn nó và ghi bất kỳ nội dung mới nào bạn truyền vào.

Nếu tệp zip đích không tồn tại, thì

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẽ tạo nó cho bạn khi bạn đóng kho lưu trữ:

Sau khi chạy mã này, bạn sẽ có tệp with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:18 trong thư mục >>> import zipfile >>> with zipfile.ZipFile("sample.zip", mode="r") as archive: ... archive.printdir() ... File Name Modified Size hello.txt 2021-09-07 19:50:10 83 lorem.md 2021-09-07 19:50:10 2609 realpython.md 2021-09-07 19:50:10 428 7 của bạn. Nếu bạn liệt kê nội dung tệp bằng >>> import zipfile >>> try: ... with zipfile.ZipFile("sample.zip") as archive: ... archive.printdir() ... except zipfile.BadZipFile as error: ... print(error) ... File Name Modified Size hello.txt 2021-09-07 19:50:10 83 lorem.md 2021-09-07 19:50:10 2609 realpython.md 2021-09-07 19:50:10 428 >>> try: ... with zipfile.ZipFile("bad_sample.zip") as archive: ... archive.printdir() ... except zipfile.BadZipFile as error: ... print(error) ... File is not a zip file 6, thì bạn sẽ nhận thấy rằng with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:17 sẽ ở đó. Trong ví dụ này, bạn gọi with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:27 trên đối tượng import os import zipfile import tempfile def updateZip(zipname, filename, data): # generate a temp file tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname)) os.close(tmpfd) # create a temp copy of the archive without filename with zipfile.ZipFile(zipname, 'r') as zin: with zipfile.ZipFile(tmpname, 'w') as zout: zout.comment = zin.comment # preserve the comment for item in zin.infolist(): if item.filename != filename: zout.writestr(item, zin.read(item.filename)) # replace with the temp archive os.remove(zipname) os.rename(tmpname, zipname) # now add filename with its new data with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, data) msg = 'This data did not exist in a file before being added to the ZIP file' updateZip('1.zip', 'index.html', msg) 9. Phương pháp này cho phép bạn viết các tệp thành viên vào kho lưu trữ zip của bạn. Lưu ý rằng đối số thành with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:27 phải là một tệp hiện có.

Chế độ phụ lục (

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3) cho phép bạn nối các tệp thành viên mới vào tệp zip hiện có. Chế độ này không cắt ngắn kho lưu trữ, vì vậy nội dung ban đầu của nó là an toàn. Nếu tệp zip đích không tồn tại, thì chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3 sẽ tạo một tệp mới cho bạn và sau đó nối thêm bất kỳ tệp đầu vào nào bạn chuyển dưới dạng đối số cho
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27.

Để thử chế độ

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3, hãy tiếp tục và thêm tệp
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34 vào kho lưu trữ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
18 mới được tạo của bạn:

Tại đây, bạn sử dụng chế độ phụ lục để thêm
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34 vào tệp
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
18. Sau đó, bạn chạy
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6 để xác nhận rằng tệp mới có trong tệp zip.
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 cũng hỗ trợ chế độ độc quyền (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
4). Chế độ này cho phép bạn độc quyền tạo các tệp zip mới và ghi các tệp thành viên mới vào chúng. Bạn sẽ sử dụng chế độ độc quyền khi bạn muốn tạo một tệp zip mới mà không ghi đè lên một tệp hiện có. Nếu tệp đích đã tồn tại, thì bạn sẽ nhận được
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
41.
Cuối cùng, nếu bạn tạo một tệp zip bằng chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2,
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3 hoặc
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
4 và sau đó đóng kho lưu trữ mà không cần thêm bất kỳ tệp thành viên nào, thì
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẽ tạo một kho lưu trữ trống với định dạng zip thích hợp.
Đọc siêu dữ liệu từ các tệp zip
Bạn đã đưa
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6 vào hành động. Nó là một phương pháp hữu ích mà bạn có thể sử dụng để liệt kê nội dung của các tệp zip của mình một cách nhanh chóng. Cùng với
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6, lớp
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 cung cấp một số phương thức tiện dụng để trích xuất siêu dữ liệu từ các tệp zip hiện có.
Ở đây, một bản tóm tắt của các phương pháp sau:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
55
Trả về một danh sách giữ tên của tất cả các tệp thành viên trong kho lưu trữ cơ bản. Các tên trong danh sách này là các đối số hợp lệ cho
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56.

Với ba công cụ này, bạn có thể truy xuất rất nhiều thông tin hữu ích về nội dung của các tệp zip của mình. Ví dụ: hãy xem ví dụ sau, sử dụng

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56:

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
3

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

Với

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
53, bạn có thể trích xuất thông tin từ tất cả các tệp trong một kho lưu trữ nhất định. Dưới đây, một ví dụ sử dụng phương thức này để tạo báo cáo tối thiểu với thông tin về tất cả các tệp thành viên trong kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 của bạn:

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
4

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
5

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

Với with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:53, bạn có thể trích xuất thông tin từ tất cả các tệp trong một kho lưu trữ nhất định. Dưới đây, một ví dụ sử dụng phương thức này để tạo báo cáo tối thiểu với thông tin về tất cả các tệp thành viên trong kho lưu trữ >>> import zipfile >>> with zipfile.ZipFile("sample.zip", mode="r") as archive: ... archive.printdir() ... File Name Modified Size hello.txt 2021-09-07 19:50:10 83 lorem.md 2021-09-07 19:50:10 2609 realpython.md 2021-09-07 19:50:10 428 8 của bạn:

Vòng lặp

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
67 lặp lại các đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 từ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
53, truy xuất tên tệp, ngày sửa đổi cuối cùng, kích thước bình thường và kích thước nén của mỗi tệp thành viên. Trong ví dụ này, bạn đã sử dụng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
70 để định dạng ngày theo cách có thể đọc được của con người.

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
6

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
7

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

Với

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
53, bạn có thể trích xuất thông tin từ tất cả các tệp trong một kho lưu trữ nhất định. Dưới đây, một ví dụ sử dụng phương thức này để tạo báo cáo tối thiểu với thông tin về tất cả các tệp thành viên trong kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 của bạn:

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
8

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

>>>

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
9

Như bạn đã học trong bảng trên,

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
56 lấy một tệp thành viên làm đối số và trả về một đối tượng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 với thông tin về nó.

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
50 Đối tượng có một số thuộc tính cho phép bạn truy xuất thông tin có giá trị về tệp thành viên đích. Ví dụ:
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
61 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
62 giữ kích thước, tính theo byte, của các tệp gốc và được nén, tương ứng. Lớp cũng có một số thuộc tính hữu ích khác, chẳng hạn như
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
63 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
64, trả về tên tệp và ngày sửa đổi cuối cùng.

>>>

for inzipinfo in inzip.infolist():
0

Trong ví dụ này, bạn mở

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 để đọc. Đối số đầu tiên cho
for inzipinfo in inzip.infolist():
13 là
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
81, cho biết tệp thành viên mà bạn muốn mở. Đối số thứ hai là chế độ, mặc định là
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
1 như bình thường.
for inzipinfo in inzip.infolist():
09 cũng chấp nhận đối số
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
89 để mở các tệp được mã hóa. Đối số này hoạt động giống như đối số
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
89 tương đương trong
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
9.

Bạn cũng có thể sử dụng

for inzipinfo in inzip.infolist():
13 với chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2. Chế độ này cho phép bạn tạo một tệp thành viên mới, ghi nội dung vào nó và cuối cùng nối tệp vào kho lưu trữ bên dưới, bạn nên mở ở chế độ nối:

>>>

for inzipinfo in inzip.infolist():
1

Trong đoạn mã đầu tiên, bạn mở

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 ở chế độ phụ trợ (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3). Sau đó, bạn tạo
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34 bằng cách gọi
for inzipinfo in inzip.infolist():
13 với chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2. Hàm này trả về một đối tượng giống như tệp hỗ trợ
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27, cho phép bạn viết byte vào tệp mới được tạo.

Trong ví dụ này, bạn viết

for inzipinfo in inzip.infolist():
28 vào
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34. Khi luồng thực thi thoát khỏi câu lệnh
outzip.writestr("test.txt", content)
5 bên trong, Python ghi các byte đầu vào vào tệp thành viên. Khi câu lệnh
outzip.writestr("test.txt", content)
5 bên ngoài thoát ra, Python viết
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34 vào tệp zip bên dưới,
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8.

Đoạn mã thứ hai xác nhận rằng

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
34 hiện là tệp thành viên là
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8. Một chi tiết cần chú ý trong đầu ra của ví dụ này là
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27 đặt ngày
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
01 của tệp mới được thêm vào
for inzipinfo in inzip.infolist():
38, đây là một hành vi kỳ lạ mà bạn nên ghi nhớ khi sử dụng phương pháp này.

Đọc nội dung của các tệp thành viên dưới dạng văn bản

Như bạn đã học trong phần trên, bạn có thể sử dụng các phương thức

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
9 và
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27 để đọc và ghi vào các tệp thành viên mà không trích xuất chúng từ kho lưu trữ zip chứa. Cả hai phương pháp này hoạt động độc quyền với byte.

Tuy nhiên, khi bạn có kho lưu trữ có chứa các tệp văn bản, bạn có thể muốn đọc nội dung của họ dưới dạng văn bản thay vì là byte. Có ít nhất hai cách để làm điều này. Bạn có thể dùng:

  1. for inzipinfo in inzip.infolist():
    41
  2. for inzipinfo in inzip.infolist():
    42

Bởi vì

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
88 trả về nội dung của tệp thành viên đích như byte,
for inzipinfo in inzip.infolist():
44 có thể hoạt động trực tiếp trên các byte này. Phương thức
for inzipinfo in inzip.infolist():
44 giải mã đối tượng
for inzipinfo in inzip.infolist():
46 thành một chuỗi bằng định dạng mã hóa ký tự nhất định.

Tại đây, cách bạn có thể sử dụng

for inzipinfo in inzip.infolist():
44 để đọc văn bản từ tệp
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 trong kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 của bạn:

>>>

for inzipinfo in inzip.infolist():
2

Trong ví dụ này, bạn đọc nội dung của

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 dưới dạng byte. Sau đó, bạn gọi
for inzipinfo in inzip.infolist():
44 để giải mã byte thành một chuỗi bằng UTF-8 làm mã hóa. Để đặt đối số
for inzipinfo in inzip.infolist():
52, bạn sử dụng chuỗi
for inzipinfo in inzip.infolist():
53. Tuy nhiên, bạn có thể sử dụng bất kỳ mã hóa hợp lệ nào khác, chẳng hạn như UTF-16 hoặc CP1252, có thể được biểu diễn dưới dạng các chuỗi không nhạy cảm trường hợp. Lưu ý rằng
for inzipinfo in inzip.infolist():
53 là giá trị mặc định của đối số
for inzipinfo in inzip.infolist():
52 thành
for inzipinfo in inzip.infolist():
44.

Điều quan trọng là phải nhớ rằng bạn cần biết trước định dạng mã hóa ký tự của bất kỳ tệp thành viên nào mà bạn muốn xử lý bằng cách sử dụng

for inzipinfo in inzip.infolist():
44. Nếu bạn sử dụng mã hóa ký tự sai, thì mã của bạn sẽ không giải mã chính xác các byte bên dưới thành văn bản và bạn có thể kết thúc với một tấn ký tự không thể giải mã được.

Tùy chọn thứ hai để đọc văn bản trong tệp thành viên là sử dụng đối tượng

for inzipinfo in inzip.infolist():
42, cung cấp luồng văn bản được đệm. Lần này bạn cần sử dụng
for inzipinfo in inzip.infolist():
13 thay vì
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
9. Ở đây, một ví dụ về việc sử dụng
for inzipinfo in inzip.infolist():
42 để đọc nội dung của tệp thành viên
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 dưới dạng luồng văn bản:

>>>

for inzipinfo in inzip.infolist():
3

Trong câu lệnh

outzip.writestr("test.txt", content)
5 bên trong trong ví dụ này, bạn mở tệp thành viên
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 từ kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 của bạn. Sau đó, bạn vượt qua đối tượng giống như tệp nhị phân,
for inzipinfo in inzip.infolist():
66, như một đối số cho
for inzipinfo in inzip.infolist():
42. Điều này tạo ra một luồng văn bản được đệm bằng cách giải mã nội dung của
for inzipinfo in inzip.infolist():
66 bằng định dạng mã hóa ký tự UTF-8. Do đó, bạn nhận được một luồng văn bản trực tiếp từ tệp thành viên mục tiêu của mình.

Giống như với

for inzipinfo in inzip.infolist():
69, lớp
for inzipinfo in inzip.infolist():
42 có một đối số
for inzipinfo in inzip.infolist():
52. Bạn phải luôn chỉ định một giá trị cho đối số này vì mã hóa văn bản mặc định phụ thuộc vào hệ thống chạy mã và có thể không phải là giá trị phù hợp cho tệp mà bạn đang cố gắng giải mã.

Đóng các tệp zip sau khi sử dụng

Đôi khi, nó thuận tiện cho bạn để mở một tệp zip đã cho mà không cần sử dụng câu lệnh

outzip.writestr("test.txt", content)
5. Trong những trường hợp đó, bạn cần đóng thủ công kho lưu trữ sau khi sử dụng để hoàn thành bất kỳ hoạt động viết nào và giải phóng các tài nguyên có được.

Để làm điều đó, bạn có thể gọi

for inzipinfo in inzip.infolist():
73 trên đối tượng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 của bạn:

>>>

for inzipinfo in inzip.infolist():
4

Cuộc gọi đến

for inzipinfo in inzip.infolist():
73 đóng
>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
7 cho bạn. Bạn phải gọi
for inzipinfo in inzip.infolist():
73 trước khi thoát khỏi chương trình của bạn. Nếu không, một số hoạt động viết có thể không được thực hiện. Ví dụ: nếu bạn mở tệp zip để thêm các tệp thành viên mới (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3), thì bạn cần đóng kho lưu trữ để viết các tệp.

Tạo, điền và trích xuất các tệp zip của riêng bạn

Cho đến nay, bạn đã học được cách làm việc với các tệp zip hiện có. Bạn đã học cách đọc, viết và nối các tệp thành viên vào chúng bằng cách sử dụng các chế độ khác nhau của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Bạn cũng đã học được cách đọc siêu dữ liệu có liên quan và cách trích xuất nội dung của một tệp zip đã cho.

Trong phần này, bạn sẽ mã hóa một vài ví dụ thực tế rằng sẽ giúp bạn tìm hiểu cách tạo các tệp zip từ một số tệp đầu vào và từ toàn bộ thư mục bằng cách sử dụng

outzip.writestr("test.txt", content)
0 và các công cụ Python khác. Bạn cũng sẽ học cách sử dụng
outzip.writestr("test.txt", content)
0 để nén tệp và hơn thế nữa.

Tạo tệp zip từ nhiều tệp thông thường

Đôi khi bạn cần tạo một kho lưu trữ zip từ một số tệp liên quan. Bằng cách này, bạn có thể có tất cả các tệp trong một thùng chứa duy nhất để phân phối chúng qua mạng máy tính hoặc chia sẻ chúng với bạn bè hoặc đồng nghiệp. Để kết thúc này, bạn có thể tạo một danh sách các tệp đích và ghi chúng vào kho lưu trữ bằng cách sử dụng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 và vòng lặp:

>>>

for inzipinfo in inzip.infolist():
5

Ở đây, bạn tạo một đối tượng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 với tên lưu trữ mong muốn làm đối số đầu tiên của nó. Chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2 cho phép bạn viết các tệp thành viên vào tệp zip cuối cùng.

Vòng lặp

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
67 lặp lại danh sách các tệp đầu vào của bạn và ghi chúng vào tệp ZIP bên dưới bằng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27. Khi luồng thực thi thoát ra câu lệnh
outzip.writestr("test.txt", content)
5,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẽ tự động đóng kho lưu trữ, lưu các thay đổi cho bạn. Bây giờ bạn có kho lưu trữ
for inzipinfo in inzip.infolist():
89 chứa tất cả các tệp từ danh sách các tệp ban đầu của bạn.

Xây dựng tệp zip từ một thư mục

Kết hợp nội dung của một thư mục vào một kho lưu trữ là một trường hợp sử dụng hàng ngày khác cho các tệp zip. Python có một số công cụ mà bạn có thể sử dụng với

outzip.writestr("test.txt", content)
0 để tiếp cận nhiệm vụ này. Ví dụ: bạn có thể sử dụng
outzip.writestr("test.txt", content)
6 để đọc nội dung của một thư mục nhất định. Với thông tin đó, bạn có thể tạo một kho lưu trữ container bằng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Trong thư mục

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
7, bạn có một thư mục con được gọi là
for inzipinfo in inzip.infolist():
94, với nội dung sau:

for inzipinfo in inzip.infolist():
6

Trong

for inzipinfo in inzip.infolist():
94, bạn chỉ có ba tệp thông thường. Bởi vì thư mục không chứa các thư mục con, bạn có thể sử dụng
for inzipinfo in inzip.infolist():
96 để lặp lại nội dung của nó trực tiếp. Với ý tưởng này, ở đây, cách bạn có thể xây dựng một tệp zip từ nội dung của
for inzipinfo in inzip.infolist():
94:

>>>

for inzipinfo in inzip.infolist():
7

Ở đây, bạn tạo một đối tượng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 với tên lưu trữ mong muốn làm đối số đầu tiên của nó. Chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2 cho phép bạn viết các tệp thành viên vào tệp zip cuối cùng.

Vòng lặp

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
67 lặp lại danh sách các tệp đầu vào của bạn và ghi chúng vào tệp ZIP bên dưới bằng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27. Khi luồng thực thi thoát ra câu lệnh
outzip.writestr("test.txt", content)
5,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẽ tự động đóng kho lưu trữ, lưu các thay đổi cho bạn. Bây giờ bạn có kho lưu trữ
for inzipinfo in inzip.infolist():
89 chứa tất cả các tệp từ danh sách các tệp ban đầu của bạn.

Xây dựng tệp zip từ một thư mục

Kết hợp nội dung của một thư mục vào một kho lưu trữ là một trường hợp sử dụng hàng ngày khác cho các tệp zip. Python có một số công cụ mà bạn có thể sử dụng với

outzip.writestr("test.txt", content)
0 để tiếp cận nhiệm vụ này. Ví dụ: bạn có thể sử dụng
outzip.writestr("test.txt", content)
6 để đọc nội dung của một thư mục nhất định. Với thông tin đó, bạn có thể tạo một kho lưu trữ container bằng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Trong thư mục

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
7, bạn có một thư mục con được gọi là
for inzipinfo in inzip.infolist():
94, với nội dung sau:

for inzipinfo in inzip.infolist():
8

Trong

for inzipinfo in inzip.infolist():
94, bạn chỉ có ba tệp thông thường. Bởi vì thư mục không chứa các thư mục con, bạn có thể sử dụng
for inzipinfo in inzip.infolist():
96 để lặp lại nội dung của nó trực tiếp. Với ý tưởng này, ở đây, cách bạn có thể xây dựng một tệp zip từ nội dung của
for inzipinfo in inzip.infolist():
94:

Trong ví dụ này, bạn tạo một đối tượng

for inzipinfo in inzip.infolist():
98 từ thư mục nguồn của bạn. Tuyên bố
outzip.writestr("test.txt", content)
5 đầu tiên tạo ra một đối tượng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẵn sàng để viết. Sau đó, cuộc gọi đến
if inzipinfo.filename == "test.txt":
01 trả về một trình lặp lại trên các mục trong thư mục cơ bản.

>>>

for inzipinfo in inzip.infolist():
9

Ở đây, bạn tạo một đối tượng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 với tên lưu trữ mong muốn làm đối số đầu tiên của nó. Chế độ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
2 cho phép bạn viết các tệp thành viên vào tệp zip cuối cùng.

Vòng lặp

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
67 lặp lại danh sách các tệp đầu vào của bạn và ghi chúng vào tệp ZIP bên dưới bằng
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
27. Khi luồng thực thi thoát ra câu lệnh
outzip.writestr("test.txt", content)
5,
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 sẽ tự động đóng kho lưu trữ, lưu các thay đổi cho bạn. Bây giờ bạn có kho lưu trữ
for inzipinfo in inzip.infolist():
89 chứa tất cả các tệp từ danh sách các tệp ban đầu của bạn.

Xây dựng tệp zip từ một thư mục

Kết hợp nội dung của một thư mục vào một kho lưu trữ là một trường hợp sử dụng hàng ngày khác cho các tệp zip. Python có một số công cụ mà bạn có thể sử dụng với

outzip.writestr("test.txt", content)
0 để tiếp cận nhiệm vụ này. Ví dụ: bạn có thể sử dụng
outzip.writestr("test.txt", content)
6 để đọc nội dung của một thư mục nhất định. Với thông tin đó, bạn có thể tạo một kho lưu trữ container bằng
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Thông thường, bạn sẽ sử dụng thuật ngữ được lưu trữ để tham khảo các tệp thành viên được ghi vào tệp zip mà không cần nén. Đó là lý do tại sao phương thức nén mặc định của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 được gọi là zip_stored, thực sự đề cập đến các tệp thành viên không nén được lưu trữ trong kho lưu trữ có chứa.stored to refer to member files written into a ZIP file without compression. That’s why the default compression method of
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 is called ZIP_STORED, which actually refers to uncompressed member files that are simply stored in the containing archive.

Phương pháp

if inzipinfo.filename == "test.txt":
24 là đối số thứ ba cho trình khởi tạo của
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Nếu bạn muốn nén các tệp của mình trong khi bạn viết chúng vào kho lưu trữ zip, thì bạn có thể đặt đối số này thành một trong các hằng số sau:

Không thay đổiPhương pháp nénMô -đun cần thiết
if inzipinfo.filename == "test.txt":
26
Xì hơi
outzip.writestr(inzipinfo.filename, infile.read())
8
if inzipinfo.filename == "test.txt":
28
BZIP2
outzip.writestr(inzipinfo.filename, infile.read())
9
if inzipinfo.filename == "test.txt":
30
LZMA
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
0

Đây là các phương pháp nén mà bạn hiện có thể sử dụng với

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9. Một phương pháp khác sẽ tăng
if inzipinfo.filename == "test.txt":
33. Không có phương pháp nén bổ sung nào có sẵn cho
outzip.writestr("test.txt", content)
0 kể từ Python 3.10.

Như một yêu cầu bổ sung, nếu bạn chọn một trong các phương thức này, thì mô -đun nén hỗ trợ nó phải có sẵn trong cài đặt Python của bạn. Nếu không, bạn sẽ nhận được một ngoại lệ

with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
94 và mã của bạn sẽ bị hỏng.

Một đối số có liên quan khác của

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 khi nén các tệp của bạn là
if inzipinfo.filename == "test.txt":
37. Đối số này kiểm soát mức độ nén bạn sử dụng.

Với phương pháp độ lệch,

if inzipinfo.filename == "test.txt":
37 có thể lấy số nguyên từ
if inzipinfo.filename == "test.txt":
39 đến
if inzipinfo.filename == "test.txt":
40. Với phương pháp BZIP2, bạn có thể chuyển các số nguyên từ
if inzipinfo.filename == "test.txt":
41 đến
if inzipinfo.filename == "test.txt":
40. Trong cả hai trường hợp, khi mức độ nén tăng, bạn sẽ được nén cao hơn và tốc độ nén thấp hơn.

Bây giờ nói rằng bạn muốn lưu trữ và nén nội dung của một thư mục nhất định bằng phương thức độ lệch, đây là phương thức được sử dụng phổ biến nhất trong các tệp zip. Để làm điều đó, bạn có thể chạy mã sau:

>>>

if inzipinfo.filename == "test.txt":
0

Trong ví dụ này, bạn chuyển

if inzipinfo.filename == "test.txt":
40 đến
if inzipinfo.filename == "test.txt":
37 để có được nén tối đa. Để cung cấp đối số này, bạn sử dụng một đối số từ khóa. Bạn cần phải làm điều này bởi vì
if inzipinfo.filename == "test.txt":
37 không phải là đối số vị trí thứ tư cho trình khởi tạo
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Sau khi chạy mã này, bạn sẽ có một tệp

if inzipinfo.filename == "test.txt":
47 trong thư mục hiện tại của bạn. Nếu bạn so sánh kích thước của tệp đó với kích thước của tệp
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 ban đầu của bạn, thì bạn sẽ lưu ý giảm kích thước đáng kể.

Tạo các tệp zip theo tuần tự

Tạo các tệp ZIP tuần tự có thể là một yêu cầu phổ biến khác trong lập trình hàng ngày của bạn. Ví dụ: bạn có thể cần tạo một tệp zip ban đầu có hoặc không có nội dung và sau đó nối các tệp thành viên mới ngay khi chúng có sẵn. Trong tình huống này, bạn cần mở và đóng tệp zip đích nhiều lần.

Để giải quyết vấn đề này, bạn có thể sử dụng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 trong chế độ phụ trợ (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3), như bạn đã thực hiện. Chế độ này cho phép bạn nối các tệp thành viên mới một cách an toàn vào kho lưu trữ zip mà không cần cắt ngắn nội dung hiện tại của nó:

>>>

if inzipinfo.filename == "test.txt":
1

Trong ví dụ này, bạn chuyển

if inzipinfo.filename == "test.txt":
40 đến
if inzipinfo.filename == "test.txt":
37 để có được nén tối đa. Để cung cấp đối số này, bạn sử dụng một đối số từ khóa. Bạn cần phải làm điều này bởi vì
if inzipinfo.filename == "test.txt":
37 không phải là đối số vị trí thứ tư cho trình khởi tạo
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Sau khi chạy mã này, bạn sẽ có một tệp

if inzipinfo.filename == "test.txt":
47 trong thư mục hiện tại của bạn. Nếu bạn so sánh kích thước của tệp đó với kích thước của tệp
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 ban đầu của bạn, thì bạn sẽ lưu ý giảm kích thước đáng kể.

Tạo các tệp zip theo tuần tự

Tạo các tệp ZIP tuần tự có thể là một yêu cầu phổ biến khác trong lập trình hàng ngày của bạn. Ví dụ: bạn có thể cần tạo một tệp zip ban đầu có hoặc không có nội dung và sau đó nối các tệp thành viên mới ngay khi chúng có sẵn. Trong tình huống này, bạn cần mở và đóng tệp zip đích nhiều lần.

Để giải quyết vấn đề này, bạn có thể sử dụng

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 trong chế độ phụ trợ (
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
3), như bạn đã thực hiện. Chế độ này cho phép bạn nối các tệp thành viên mới một cách an toàn vào kho lưu trữ zip mà không cần cắt ngắn nội dung hiện tại của nó:

>>>

if inzipinfo.filename == "test.txt":
2

Trong ví dụ này, bạn chuyển

if inzipinfo.filename == "test.txt":
40 đến
if inzipinfo.filename == "test.txt":
37 để có được nén tối đa. Để cung cấp đối số này, bạn sử dụng một đối số từ khóa. Bạn cần phải làm điều này bởi vì
if inzipinfo.filename == "test.txt":
37 không phải là đối số vị trí thứ tư cho trình khởi tạo
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9.

Sau khi chạy mã này, bạn sẽ có một tệp if inzipinfo.filename == "test.txt":47 trong thư mục hiện tại của bạn. Nếu bạn so sánh kích thước của tệp đó với kích thước của tệp >>> import zipfile >>> with zipfile.ZipFile("sample.zip", mode="r") as archive: ... archive.printdir() ... File Name Modified Size hello.txt 2021-09-07 19:50:10 83 lorem.md 2021-09-07 19:50:10 2609 realpython.md 2021-09-07 19:50:10 428 8 ban đầu của bạn, thì bạn sẽ lưu ý giảm kích thước đáng kể.

Tạo các tệp zip theo tuần tự

Tìm if inzipinfo.filename == "test.txt":77 trong tệp zip

Khi bạn mở một tệp zip với ứng dụng Archiver yêu thích của bạn, bạn sẽ thấy cấu trúc bên trong kho lưu trữ. Bạn có thể có các tệp ở gốc của kho lưu trữ. Bạn cũng có thể có thư mục con với nhiều tệp hơn. Lưu trữ trông giống như một thư mục bình thường trên hệ thống tệp của bạn, với mỗi tệp nằm ở một đường dẫn cụ thể.

Lớp

if inzipinfo.filename == "test.txt":
75 cho phép bạn xây dựng các đối tượng đường dẫn để nhanh chóng tạo và quản lý các đường dẫn đến các tệp và thư mục thành viên bên trong một tệp zip đã cho. Lớp học có hai đối số:

  • if inzipinfo.filename == "test.txt":
    79 chấp nhận tệp zip, dưới dạng đối tượng
    import os
    import zipfile
    import tempfile
    
    def updateZip(zipname, filename, data):
        # generate a temp file
        tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
        os.close(tmpfd)
    
        # create a temp copy of the archive without filename            
        with zipfile.ZipFile(zipname, 'r') as zin:
            with zipfile.ZipFile(tmpname, 'w') as zout:
                zout.comment = zin.comment # preserve the comment
                for item in zin.infolist():
                    if item.filename != filename:
                        zout.writestr(item, zin.read(item.filename))
    
        # replace with the temp archive
        os.remove(zipname)
        os.rename(tmpname, zipname)
    
        # now add filename with its new data
        with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            zf.writestr(filename, data)
    
    msg = 'This data did not exist in a file before being added to the ZIP file'
    updateZip('1.zip', 'index.html', msg)
    
    9 hoặc đường dẫn dựa trên chuỗi đến tệp zip vật lý.
    accepts a ZIP file, either as a
    import os
    import zipfile
    import tempfile
    
    def updateZip(zipname, filename, data):
        # generate a temp file
        tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
        os.close(tmpfd)
    
        # create a temp copy of the archive without filename            
        with zipfile.ZipFile(zipname, 'r') as zin:
            with zipfile.ZipFile(tmpname, 'w') as zout:
                zout.comment = zin.comment # preserve the comment
                for item in zin.infolist():
                    if item.filename != filename:
                        zout.writestr(item, zin.read(item.filename))
    
        # replace with the temp archive
        os.remove(zipname)
        os.rename(tmpname, zipname)
    
        # now add filename with its new data
        with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            zf.writestr(filename, data)
    
    msg = 'This data did not exist in a file before being added to the ZIP file'
    updateZip('1.zip', 'index.html', msg)
    
    9 object or a string-based path to a physical ZIP file.
  • if inzipinfo.filename == "test.txt":
    81 giữ vị trí của một tệp hoặc thư mục thành viên cụ thể bên trong kho lưu trữ. Nó mặc định là chuỗi trống, đại diện cho gốc của kho lưu trữ.
    holds the location of a specific member file or directory inside the archive. It defaults to the empty string, representing the root of the archive.

Với người bạn cũ của bạn

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 làm mục tiêu, hãy chạy mã sau:

>>>

if inzipinfo.filename == "test.txt":
3

Mã này cho thấy

if inzipinfo.filename == "test.txt":
75 thực hiện một số tính năng phổ biến đối với đối tượng
for inzipinfo in inzip.infolist():
98. Bạn có thể lấy tên của tệp với
if inzipinfo.filename == "test.txt":
85. Bạn có thể kiểm tra xem đường dẫn chỉ vào một tệp thông thường với
if inzipinfo.filename == "test.txt":
86. Bạn có thể kiểm tra xem một tệp nhất định có tồn tại bên trong một tệp zip cụ thể không và hơn thế nữa.

if inzipinfo.filename == "test.txt":
77 cũng cung cấp một phương thức
for inzipinfo in inzip.infolist():
13 để mở tệp thành viên bằng các chế độ khác nhau. Ví dụ: mã bên dưới mở
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 để đọc:

>>>

if inzipinfo.filename == "test.txt":
4

Mã này cho thấy

if inzipinfo.filename == "test.txt":
75 thực hiện một số tính năng phổ biến đối với đối tượng
for inzipinfo in inzip.infolist():
98. Bạn có thể lấy tên của tệp với
if inzipinfo.filename == "test.txt":
85. Bạn có thể kiểm tra xem đường dẫn chỉ vào một tệp thông thường với
if inzipinfo.filename == "test.txt":
86. Bạn có thể kiểm tra xem một tệp nhất định có tồn tại bên trong một tệp zip cụ thể không và hơn thế nữa.

if inzipinfo.filename == "test.txt":
77 cũng cung cấp một phương thức
for inzipinfo in inzip.infolist():
13 để mở tệp thành viên bằng các chế độ khác nhau. Ví dụ: mã bên dưới mở
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 để đọc:

>>>

if inzipinfo.filename == "test.txt":
5

Mã này cho thấy

if inzipinfo.filename == "test.txt":
75 thực hiện một số tính năng phổ biến đối với đối tượng
for inzipinfo in inzip.infolist():
98. Bạn có thể lấy tên của tệp với
if inzipinfo.filename == "test.txt":
85. Bạn có thể kiểm tra xem đường dẫn chỉ vào một tệp thông thường với
if inzipinfo.filename == "test.txt":
86. Bạn có thể kiểm tra xem một tệp nhất định có tồn tại bên trong một tệp zip cụ thể không và hơn thế nữa.

if inzipinfo.filename == "test.txt":77 cũng cung cấp một phương thức for inzipinfo in inzip.infolist():13 để mở tệp thành viên bằng các chế độ khác nhau. Ví dụ: mã bên dưới mở with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:17 để đọc:

Với

if inzipinfo.filename == "test.txt":
77, bạn có thể nhanh chóng tạo một đối tượng đường dẫn trỏ đến một tệp thành viên cụ thể trong một tệp zip nhất định và truy cập nội dung của nó ngay lập tức bằng cách sử dụng
for inzipinfo in inzip.infolist():
13.

Giống như với đối tượng

for inzipinfo in inzip.infolist():
98, bạn có thể liệt kê nội dung của tệp zip bằng cách gọi
if inzipinfo.filename == "test.txt":
01 trên đối tượng
if inzipinfo.filename == "test.txt":
75:

Nó rõ ràng rằng

if inzipinfo.filename == "test.txt":
75 cung cấp nhiều tính năng hữu ích mà bạn có thể sử dụng để quản lý các tệp thành viên trong kho lưu trữ zip của mình gần như không có thời gian.importable ZIP files to distribute your modules and packages as a single archive.

Xây dựng các tệp zip có thể nhập với

if inzipinfo.filename == "test.txt":
96

Một lớp hữu ích khác trong

outzip.writestr("test.txt", content)
0 là
if inzipinfo.filename == "test.txt":
96. Lớp này khá giống với
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 và nó đặc biệt tiện dụng khi bạn cần gói các mô -đun và gói Python thành các tệp ZIP. Sự khác biệt chính từ
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9 là bộ khởi tạo của
if inzipinfo.filename == "test.txt":
96 có một đối số tùy chọn gọi là
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
02, cho phép bạn tối ưu hóa mã Python bằng cách biên dịch nó thành mã byte trước khi lưu trữ nó.

if inzipinfo.filename == "test.txt":
6

if inzipinfo.filename == "test.txt":
96 cung cấp giao diện tương tự như
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
9, với việc bổ sung
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
05. Phương thức này có thể lấy tệp Python (
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
06) làm đối số và thêm nó vào tệp zip bên dưới. Nếu
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
02 là
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
08 (mặc định), thì tệp
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
06 được tự động biên dịch thành tệp
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
10 và sau đó được thêm vào kho lưu trữ đích. Lý do tại sao điều này xảy ra?

>>>

if inzipinfo.filename == "test.txt":
7

Mã này cho thấy

if inzipinfo.filename == "test.txt":
75 thực hiện một số tính năng phổ biến đối với đối tượng
for inzipinfo in inzip.infolist():
98. Bạn có thể lấy tên của tệp với
if inzipinfo.filename == "test.txt":
85. Bạn có thể kiểm tra xem đường dẫn chỉ vào một tệp thông thường với
if inzipinfo.filename == "test.txt":
86. Bạn có thể kiểm tra xem một tệp nhất định có tồn tại bên trong một tệp zip cụ thể không và hơn thế nữa.

if inzipinfo.filename == "test.txt":
77 cũng cung cấp một phương thức
for inzipinfo in inzip.infolist():
13 để mở tệp thành viên bằng các chế độ khác nhau. Ví dụ: mã bên dưới mở
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 để đọc:

>>>

if inzipinfo.filename == "test.txt":
8

Mã này cho thấy

if inzipinfo.filename == "test.txt":
75 thực hiện một số tính năng phổ biến đối với đối tượng
for inzipinfo in inzip.infolist():
98. Bạn có thể lấy tên của tệp với
if inzipinfo.filename == "test.txt":
85. Bạn có thể kiểm tra xem đường dẫn chỉ vào một tệp thông thường với
if inzipinfo.filename == "test.txt":
86. Bạn có thể kiểm tra xem một tệp nhất định có tồn tại bên trong một tệp zip cụ thể không và hơn thế nữa.search path for modules. To add a new item to
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
24, you can use
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
26.

if inzipinfo.filename == "test.txt":
77 cũng cung cấp một phương thức
for inzipinfo in inzip.infolist():
13 để mở tệp thành viên bằng các chế độ khác nhau. Ví dụ: mã bên dưới mở
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 để đọc:

Với

if inzipinfo.filename == "test.txt":
77, bạn có thể nhanh chóng tạo một đối tượng đường dẫn trỏ đến một tệp thành viên cụ thể trong một tệp zip nhất định và truy cập nội dung của nó ngay lập tức bằng cách sử dụng
for inzipinfo in inzip.infolist():
13.

if inzipinfo.filename == "test.txt":
9

Giống như với đối tượng

for inzipinfo in inzip.infolist():
98, bạn có thể liệt kê nội dung của tệp zip bằng cách gọi
if inzipinfo.filename == "test.txt":
01 trên đối tượng
if inzipinfo.filename == "test.txt":
75:

>>>

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
0

Cuộc gọi đến

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
05 lấy gói
for inzipinfo in inzip.infolist():
66 làm đối số, tìm kiếm các tệp
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
06 bên trong nó, biên dịch chúng vào các tệp
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
10 và cuối cùng thêm chúng vào tệp zip đích,
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
18. Một lần nữa, bạn có thể nhập mã của mình từ kho lưu trữ này bằng cách làm theo các bước bạn đã học trước đây:

>>>

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
1

Vì mã của bạn hiện đang ở trong một gói, trước tiên bạn cần nhập mô -đun

for inzipinfo in inzip.infolist():
66 từ gói
for inzipinfo in inzip.infolist():
66. Sau đó, bạn có thể truy cập chức năng
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
16 của mình bình thường.

Chạy outzip.writestr("test.txt", content)0 từ dòng lệnh của bạn

Python sườn

outzip.writestr("test.txt", content)
0 cũng cung cấp một giao diện dòng lệnh tối thiểu cho phép bạn truy cập một cách nhanh chóng chức năng chính của mô-đun. Ví dụ: bạn có thể sử dụng tùy chọn
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
42 hoặc
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
43 để liệt kê nội dung của tệp zip hiện có:

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
2

Lệnh này hiển thị đầu ra giống như một cuộc gọi tương đương với

>>> import zipfile

>>> try:
...     with zipfile.ZipFile("sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428

>>> try:
...     with zipfile.ZipFile("bad_sample.zip") as archive:
...         archive.printdir()
... except zipfile.BadZipFile as error:
...     print(error)
...
File is not a zip file
6 trên kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8.

Bây giờ nói rằng bạn muốn tạo một tệp zip mới chứa một số tệp đầu vào. Trong trường hợp đó, bạn có thể sử dụng tùy chọn

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
46 hoặc
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
47:

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
3

Lệnh này tạo một tệp

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
48 chứa các tệp
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17,
for inzipinfo in inzip.infolist():
06,
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
51 của bạn.

Điều gì sẽ xảy ra nếu bạn cần tạo một tệp zip để lưu trữ toàn bộ thư mục? Ví dụ: bạn có thể có

for inzipinfo in inzip.infolist():
94 của riêng bạn với ba tệp giống như ví dụ trên. Bạn có thể tạo tệp zip từ thư mục đó bằng cách sử dụng lệnh sau:

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
4

Với lệnh này,

outzip.writestr("test.txt", content)
0 đặt
for inzipinfo in inzip.infolist():
94 tại gốc của tệp
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
55. Như thường lệ, bạn có thể liệt kê nội dung lưu trữ bằng cách chạy
outzip.writestr("test.txt", content)
0 với tùy chọn
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
42.

Bạn cũng có thể trích xuất tất cả nội dung của một tệp zip đã cho bằng tùy chọn

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
58 hoặc
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
59 từ dòng lệnh của bạn:

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
5

Sau khi chạy lệnh này, bạn sẽ có một thư mục

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
60 mới trong thư mục làm việc của mình. Thư mục mới sẽ chứa các tệp hiện tại trong kho lưu trữ
>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 của bạn.

Tùy chọn cuối cùng mà bạn có thể sử dụng với

outzip.writestr("test.txt", content)
0 từ dòng lệnh là
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
63 hoặc
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
64. Tùy chọn này cho phép bạn kiểm tra nếu một tệp đã cho là tệp zip hợp lệ. Hãy tiếp tục và thử nó!

Sử dụng các thư viện khác để quản lý các tệp zip

Có một vài công cụ khác trong thư viện tiêu chuẩn Python mà bạn có thể sử dụng để lưu trữ, nén và giải nén các tệp của bạn ở cấp độ thấp hơn. Python sườn

outzip.writestr("test.txt", content)
0 sử dụng một số trong số này, chủ yếu cho mục đích nén. Ở đây, một bản tóm tắt của một số công cụ sau:

Mô -đunSự mô tả
outzip.writestr(inzipinfo.filename, infile.read())
8
Cho phép nén và giải nén bằng thư viện ZLIB
outzip.writestr(inzipinfo.filename, infile.read())
9
Cung cấp một giao diện để nén và giải nén dữ liệu bằng thuật toán nén BZIP2
import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
0
Cung cấp các lớp và chức năng để nén và giải nén dữ liệu bằng thuật toán nén LZMA

Không giống như

outzip.writestr("test.txt", content)
0, một số mô -đun này cho phép bạn nén và giải nén dữ liệu từ các luồng bộ nhớ và dữ liệu khác ngoài các tệp và tài liệu lưu trữ thông thường.

Trong thư viện tiêu chuẩn Python, bạn cũng sẽ tìm thấy

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
70, hỗ trợ định dạng lưu trữ TAR. Ngoài ra, còn có một mô -đun gọi là
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
71, cung cấp một giao diện để nén và giải nén dữ liệu, tương tự như cách chương trình GNU GZIP thực hiện nó.

Ví dụ: bạn có thể sử dụng

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
71 để tạo tệp nén chứa một số văn bản:

>>>

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
6

Khi bạn chạy mã này, bạn sẽ có kho lưu trữ

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
73 chứa phiên bản nén của
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17 trong thư mục hiện tại của bạn. Bên trong
with zipfile.ZipFile(srcfile) as inzip, zipfile.ZipFile(dstfile, "w") as outzip:
17, bạn sẽ tìm thấy văn bản
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
76.

Một cách nhanh chóng và cấp cao để tạo tệp zip mà không cần sử dụng

outzip.writestr("test.txt", content)
0 là sử dụng
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
78. Mô-đun này cho phép bạn thực hiện một số hoạt động cấp cao trên các tệp và bộ sưu tập tệp. Khi nói đến các hoạt động lưu trữ, bạn có
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
79, có thể tạo tài liệu lưu trữ, chẳng hạn như các tệp zip hoặc tar:

>>>

with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
7

Mã này tạo ra một tệp nén được gọi là

>>> import zipfile

>>> with zipfile.ZipFile("sample.zip", mode="r") as archive:
...     archive.printdir()
...
File Name                                        Modified             Size
hello.txt                                 2021-09-07 19:50:10           83
lorem.md                                  2021-09-07 19:50:10         2609
realpython.md                             2021-09-07 19:50:10          428
8 trong thư mục làm việc của bạn. Tệp zip này sẽ chứa tất cả các tệp trong thư mục đầu vào,
for inzipinfo in inzip.infolist():
94. Hàm
with inzip.open(inzipinfo) as infile:
    content = infile.read().replace("abc", "123")
79 thuận tiện khi bạn cần một cách nhanh chóng và cấp cao để tạo các tệp zip của bạn trong Python.

Sự kết luận

Python sườn

outzip.writestr("test.txt", content)
0 là một công cụ tiện dụng khi bạn cần đọc, ghi, nén, giải nén và trích xuất các tệp từ kho lưu trữ zip. Định dạng tệp ZIP đã trở thành một tiêu chuẩn công nghiệp, cho phép bạn đóng gói và tùy chọn nén dữ liệu kỹ thuật số của bạn.
outzip.writestr("test.txt", content)
0
is a handy tool when you need to read, write, compress, decompress, and extract files from ZIP archives. The ZIP file format has become an industry standard, allowing you to package and optionally compress your digital data.

Lợi ích của việc sử dụng các tệp ZIP bao gồm lưu trữ các tệp liên quan đến nhau, lưu không gian đĩa, giúp dễ dàng chuyển dữ liệu qua mạng máy tính, gói mã Python cho mục đích phân phối và hơn thế nữa.

Trong hướng dẫn này, bạn đã học được cách:

  • Sử dụng Python từ
    outzip.writestr("test.txt", content)
    0 để đọc, ghi và trích xuất các tệp zip hiện córead, write, and extract existing ZIP files
  • Đọc siêu dữ liệu về nội dung của các tệp zip của bạn với
    outzip.writestr("test.txt", content)
    0metadata about the content of your ZIP files with
    outzip.writestr("test.txt", content)
    0
  • Sử dụng
    outzip.writestr("test.txt", content)
    0 để thao tác các tệp thành viên trong các tệp zip hiện cómanipulate member files in existing ZIP files
  • Tạo các tệp zip của riêng bạn để lưu trữ và nén dữ liệu kỹ thuật số của bạnyour own ZIP files to archive and compress your digital data

Bạn cũng đã học cách sử dụng

outzip.writestr("test.txt", content)
0 từ dòng lệnh của mình để liệt kê, tạo và trích xuất các tệp zip của bạn.Với kiến thức này, bạn đã sẵn sàng lưu trữ, nén và thao tác hiệu quả dữ liệu kỹ thuật số của mình bằng định dạng tệp ZIP.