覆盖 ziparchive 中的文件
我的 archive.zip
包含两个文件:hello.txt
和 world.txt
我想覆盖 hello.txt
> 使用该代码创建新文件:
import zipfile
z = zipfile.ZipFile('archive.zip','a')
z.write('hello.txt')
z.close()
但它不会覆盖文件,不知何故它会创建 hello.txt
的另一个实例 - 看看 winzip 屏幕截图:
由于没有像 zipfile.remove()
这样的东西,处理这个问题的最佳方法是什么?
I have archive.zip
with two files: hello.txt
and world.txt
I want to overwrite hello.txt
file with new one with that code:
import zipfile
z = zipfile.ZipFile('archive.zip','a')
z.write('hello.txt')
z.close()
but it won't overwrite file, somehow it creates another instance of hello.txt
— take a look at winzip screenshot:
Since there is no smth like zipfile.remove()
, what's the best way to handle this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
python zipfile 模块无法做到这一点。您必须创建一个新的 zip 文件,并重新压缩第一个文件中的所有内容以及新修改的文件。
下面是一些代码来做到这一点。但请注意,它效率不高,因为它会解压缩然后重新压缩所有数据。
用法:
There's no way to do that with python zipfile module. You have to create a new zip file and recompress everything again from the first file, plus the new modified file.
Below is some code to do just that. But note that it isn't efficient, since it decompresses and then recompresses all data.
Usage:
以诺斯克洛的答案为基础。
UpdateableZipFile 继承自 ZipFile 的类,维护相同的接口,但添加了覆盖文件(通过 writestr 或 write)和删除文件的功能。
用法示例:
Building on nosklo's answer.
UpdateableZipFile A class that inherits from ZipFile, maintians the same interface but adds the ability to overwrite files (via writestr or write) and removing files.
usage example:
我的解决方案:阅读全部 ->替换->回写
my solution: read it all -> replace -> write back
我的解决方案与其他答案类似,但使用 SQLite 来管理中间文件,并提供
__getitem__
、__setitem__
和__delitem__
以获得简单的界面。默认情况下,数据库位于内存中,但如果您的 zip 大于可用内存,则可以提供临时文件路径。
当然,SQLite 内置于 Python 中,比文件系统更快
My solution is similar to the other answers but uses SQLite to manage the intermediate files and provides
__getitem__
,__setitem__
and__delitem__
for an easy interface.By default the db is in-memory but you can provide a temp file path if you have a zip larger than available memory.
And of course SQLite is built into Python and faster than the file system
基于这个答案,这是一种快速而肮脏的方法猴子补丁库存zip文件以支持文件删除(当我们等待 python:main 接受它时:
用途:
PS NSFW
Based on this answer here's a quick and dirty way to monkey patch stock zipfile to support file deletion (while we waiting for it being accepted for python:main):
Usage:
P.S. NSFW
参考:使用ZipFile模块从zip文件中删除文件
简而言之,
您可以从 https://github 获取代码.com/python/cpython/blob/659eb048cc9cac73c46349eb29845bc5cd630f09/Lib/zipfile.py 并从中创建一个单独的文件。之后,只需从项目中引用它,而不是内置 python 库:
import myproject.zipfile as zipfile
。用法:
Reference: Delete file from zipfile with the ZipFile Module
In short,
You can take the code from https://github.com/python/cpython/blob/659eb048cc9cac73c46349eb29845bc5cd630f09/Lib/zipfile.py and create a separate file from it. After that just reference it from your project instead of built-in python library:
import myproject.zipfile as zipfile
.Usage: