Python的zipfile模块无法更新条目

2024-10-01 09:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用pythonszipfile模块更新zip文件中的条目。 我的问题是这会生成一个新条目。在

请假设我有这个代码:

from zipfile import ZipFile,ZIP_DEFLATED
with ZipFile("myfile.zip","w") as z:
    z.writestr("hello.txt", "the content of hello.txt", ZIP_DEFLATED)
    ###  how to update the hello.txt file here ?
    z.writestr("hello.txt", "the content of hello.txt", ZIP_DEFLATED)

在此之后,实际的zip文件有两个条目,而不是一个条目:

^{pr2}$

我知道写一个完整的新文件的方法,但这将 如果内容很大,就要花很多时间。在

zip(1)实用程序可以做到这一点(使用“-u”选项),那么为什么python不能呢? 我还有什么办法可以用python实现这一点吗?在

谢谢


Tags: 模块文件ofthe代码txthello条目
2条回答

zip格式没有任何简单的方法来删除或替换存档中的文件。也许有一些图书馆可以这样做,但我不知道有一个。在

但是等等:

the zip(1) utitly can do this ( using the "-u" option) so why not python?

首先,-u所做的只是告诉它“只有在时间戳不更新的情况下才替换现有文件”,这在这里并不真正相关。如果没有-u它仍然会,默认命令是add,它执行相同的操作而不检查时间戳:

Update existing entries and add new files. If the archive does not exist create it. This is the default mode.

但是,更重要的是,正如the manpage you referenced明确指出的那样:

Zip files. When changing an existing zip archive, zip will write a temporary file with the new contents, and only replace the old one when the process of creating the new version has been completed without error.

而这正是你想要做的:写一个完整的新文件到一个临时位置,然后用新文件替换原来的文件。在

如果你需要让它在Windows上运行,这可能会有点痛苦。(如果没有,只需使用tempfile.NamedTemporaryFileos.rename)但您已经知道如何做:

I know of the method to write a complete new file, but this would take much time if the content is big.

不要超过zip -u花费太多时间。在

我怀疑zipfile模块是否可以像您所希望的那样修改归档文件。如果可以的话,就会有一个方法从ZipFile中删除一个文件,但是没有

相关问题 更多 >