开发者

rename files in zip folder using zipmodule

开发者 https://www.devze.com 2023-04-05 13:38 出处:网络
I was wondering if anyone knows how I can rename a file called \"logo.pn开发者_开发技巧g\" in my zip folder under (\"fw/resources/logo.png\") to (\"fw/resources/logo.png.bak\"), using python\'s zip mo

I was wondering if anyone knows how I can rename a file called "logo.pn开发者_开发技巧g" in my zip folder under ("fw/resources/logo.png") to ("fw/resources/logo.png.bak"), using python's zip module.


As mentioned by rocksportrocker, you cannot rename/remove a file from a zipfile archive. You would have iterate over the files in the zipfile and selectively add the files you want. So to remove a certain directory from the zipfile, you would not copy them to the new zipfile. That would be something like this:

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

As this would read all the files into memory, it would not be an ideal solution for large archives. For small archives this works as advertised.


I think that is not possible: the zipfile modules has no methods for that, and as mentioned in Renaming a File/Folder inside a Zip File in Java? the internal structure of zip files is in the way. So you have to do unzip, rename, zip.

Update: Just found Delete file from zipfile with the ZipFile Module which should help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号