我想用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实现这一点吗?在
谢谢
zip
格式没有任何简单的方法来删除或替换存档中的文件。也许有一些图书馆可以这样做,但我不知道有一个。在但是等等:
首先,
-u
所做的只是告诉它“只有在时间戳不更新的情况下才替换现有文件”,这在这里并不真正相关。如果没有-u
它仍然会,默认命令是add
,它执行相同的操作而不检查时间戳:但是,更重要的是,正如the manpage you referenced明确指出的那样:
而这正是你想要做的:写一个完整的新文件到一个临时位置,然后用新文件替换原来的文件。在
如果你需要让它在Windows上运行,这可能会有点痛苦。(如果没有,只需使用
tempfile.NamedTemporaryFile
和os.rename
)但您已经知道如何做:不要超过
zip -u
花费太多时间。在我怀疑
zipfile
模块是否可以像您所希望的那样修改归档文件。如果可以的话,就会有一个方法从ZipFile
中删除一个文件,但是没有相关问题 更多 >
编程相关推荐