8

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.

user715578
  • 467
  • 2
  • 8
  • 16

2 Answers2

5

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.

swdev
  • 2,941
  • 2
  • 25
  • 37
Bouke
  • 11,768
  • 7
  • 68
  • 102
4

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.

Community
  • 1
  • 1
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48