简体   繁体   English

python如何在zip存档中附加到文件

[英]python how to append to file in zip archive

If I do something like this: 如果我做这样的事情:

from zipfile import ZipFile 

zip = ZipFile(archive, "a")  

for x in range(5):
    zip.writestr("file1.txt", "blabla")

It will create an archive with 5 files all named "file1.txt". 它将创建一个包含5个文件的存档,所有文件都名为“file1.txt”。 What I want to achieve is having one compressed file to which every loop iteration appends some content. 我想要实现的是拥有一个压缩文件,每个循环迭代都附加一些内容。 Is it possible without having some kind of auxiliary buffer and how to do this? 是否有可能没有某种辅助缓冲区以及如何做到这一点?

Its quite possible to append files to compressed archive using Python. 很有可能使用Python将文件附加到压缩存档。

Tested on linux mint 14,Python 2.7 测试了linux mint 14,Python 2.7

import zipfile

#Create compressed zip archive and add files
z = zipfile.ZipFile("myzip.zip", "w",zipfile.ZIP_DEFLATED)
z.write("file1.ext")
z.write("file2.ext")
z.printdir()
z.close()

#Append files to compressed archive
z = zipfile.ZipFile("myzip.zip", "a",zipfile.ZIP_DEFLATED)
z.write("file3.ext")
z.printdir()
z.close()

#Extract all files in archive
z = zipfile.ZipFile("myzip.zip", "r",zipfile.ZIP_DEFLATED)
z.extractall("mydir")
z.close()

It's impossible with zipfile package but writing to compressed files is supported in gzip : 使用zipfile包是不可能的,但gzip支持写入压缩文件:

import gzip
content = "Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM