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()
如rocksportrocker所述,您不能重命名/从zipfile存档中删除文件。您将遍历zipfile中的文件并有选择地添加所需的文件。因此,要从zipfile中删除某个目录,您不会将它们复制到新的zipfile中。可能是这样的:
由于这会将所有文件读入内存,因此对于大型存档来说,这不是一个理想的解决方案。对于小档案馆,这是广告上说的。
我认为这是不可能的:zipfile模块没有实现这一点的方法,正如Renaming a File/Folder inside a Zip File in Java?中提到的,zip文件的内部结构阻碍了这一点。所以你必须解压缩,重命名,压缩。
更新:刚刚找到 Delete file from zipfile with the ZipFile Module对你有帮助。
相关问题 更多 >
编程相关推荐