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

2024-05-16 15:27:22 发布

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

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


Tags: 模块文件文件夹pngzip重命名logoresources
2条回答

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

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()

由于这会将所有文件读入内存,因此对于大型存档来说,这不是一个理想的解决方案。对于小档案馆,这是广告上说的。

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

更新:刚刚找到 Delete file from zipfile with the ZipFile Module对你有帮助。

相关问题 更多 >