Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename files in zip folder using zipmodule

Tags:

python

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.

like image 260
user715578 Avatar asked Sep 15 '11 09:09

user715578


People also ask

Can you Rename a file in a zipped folder?

For large Zip files, it may be faster to rename a number of files as a batch. Select multiple files and/or folders; then press F2. A dialog will display with a list of the selected files and folders. Next, rename each file or folder by clicking on it and typing in the new name.

How do I Rename a file in filemanager?

Click on File Manager in the left pane. Look for the folder or file that you want to rename. Then, click on the three-dot menu on its right side. Select Rename.

How do I change the names of files in a folder?

Find and select the file, then select File > Rename. Type the new name and press Enter.


2 Answers

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.

like image 187
Bouke Avatar answered Sep 30 '22 20:09

Bouke


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.

like image 36
rocksportrocker Avatar answered Sep 30 '22 18:09

rocksportrocker