user715578
user715578

Reputation: 467

rename files in zip folder using zipmodule

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

Upvotes: 8

Views: 16840

Answers (2)

Bouke
Bouke

Reputation: 12138

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.

Upvotes: 5

rocksportrocker
rocksportrocker

Reputation: 7419

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.

Upvotes: 4

Related Questions