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

时间:2011-09-15 09:00:03

标签: python

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:4)

正如rocksportrocker所提到的,您无法从zipfile存档重命名/删除文件。您将迭代zipfile中的文件并有选择地添加所需的文件。因此,要从zipfile中删除某个目录,您不会将它们复制到新的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()

由于这会将所有文件读入内存,因此对于大型档案来说,它不是理想的解决方案。对于小型档案馆,这就像宣传的一样。

相关问题