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.
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.
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.
Find and select the file, then select File > Rename. Type the new name and press Enter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With