-1

I am trying to write a python script to rename files (containing a predefined string with another predefined string). How do I rename files and folders in a zip file, without extracting the zip file (as it could be very large)?

import os
import zipfile
old_name="ABCD"
new_name="XYZ"

for d,s,files in os.walk(path):
 for f in files:
   if f.startswith(old_name) and f.endswith('.zip'):
     with zipfile.ZipFile(f,'a') as zf:
       for files_inside_zip in zf.namelist():
        if files_inside_zip.startswith(old_name):
          ## Now I need to rename only this particular file
          ## some files are larger than 1 GB
          ## and contains 1000+ files
          ## so extracting all doest seems to be a good idea

     zf.close  
ankur jain
  • 11
  • 3
  • Please show us some code, what you already did and what error you are getting. SO is not a place where you drop your request and others solve it for your. – codedge May 02 '20 at 10:16
  • 1
    Duplicate of [rename files in zip folder using zipmodule](https://stackoverflow.com/questions/7428318/rename-files-in-zip-folder-using-zipmodule) – Jongware May 02 '20 at 10:27
  • @codedge Updated the code I am trying to execute – ankur jain May 03 '20 at 06:10

1 Answers1

-1

There is no way of modifying a zipped archive without extracting it, in Python. One way I can think of that may solve your problem, assuming that you are on linux, is to execute a bash script in Python, that uses vim to transparently edit the archive:

Sources:
Modifying zip file in python: overwriting file in ziparchive
Executing bash script from python: Running bash script from within python
Edit zip archive with vim: https://superuser.com/questions/647674/is-there-a-way-to-edit-files-inside-of-a-zip-file-without-explicitly-extracting