使用zipmodule重命名zip文件夹中的文件

use*_*578 6 python

我想知道是否有人知道如何将我的zip文件夹("fw/resources/logo.png")中名为"logo.png"的文件重命名为("fw/resources/logo.png.bak"),使用python的zip模块.

Bou*_*uke 5

如rocksportrocker所述,您不能从zipfile存档中重命名/删除文件。您将遍历zip文件中的文件,然后有选择地添加所需的文件。因此,要从zip文件中删除某个目录,您不会将其复制到新的zip文件中。那将是这样的:

source = ZipFile('source.zip', 'r')
target = ZipFile('target.zip', 'w', ZIP_DEFLATED)
for file in source.filelist:
    if not file.filename.startswith('directory-to-remove/'):
        target.writestr(file.filename, source.read(file.filename))
target.close()
source.close()
Run Code Online (Sandbox Code Playgroud)

由于这会将所有文件读入内存,因此对于大型存档而言,这不是理想的解决方案。对于小型档案,其工作方式与广告宣传相同。


roc*_*ker 4

我认为这是不可能的:zipfile 模块没有相应的方法,正如Renaming a File/Folder inside a Zip File in Java? 中提到的那样?zip 文件的内部结构是障碍。所以你必须解压缩、重命名、压缩。

更新:刚刚找到 使用 ZipFile 模块从 zipfile 中删除文件,这应该对您有帮助。