0

I need to rename (and edit) files inside a zip file. What I'm doing so far for renaming is:

subprocess.call(["unzip", zipfile, f])
subprocess.call(["zip", "--delete", zipfile, f])
subprocess.call(["mv", f, f_new])
subprocess.call(["zip", "-qq", "-y", "--move", zipfile, f_new])

This clutters the working directory and generally seems like bad coding. Ideally I would have some way to do this inside python and preferably entirely in memory. I have looked at the zipfile module, however that doesn't seem very intuitive or well documented. It also seems to be missing some basic operations like removing files (Delete file from zipfile with the ZipFile Module). Also appending a file using zipfile corrupted my archive (I guess it uses its own compression).

Is there a more reasonable way of renaming/deleting/adding/editing zipped files than system calls?

Creating a new zip file from scratch and recompressing everything seems like an even worse option than system calls.

1 Answers1

0

I found a possible solution to that here: https://superuser.com/a/687167/1171118 It seems like you can change the filename by accessing file.filename. In the solution the person extracted the file afterwards, but as you don't want to do that, just don't copy that step.

os.rename is another option, I don't know if it works for files inside a zip tho.

riggedCoinflip
  • 435
  • 4
  • 16
  • I've looked at `file.filename` but unless I'm missing some way to "push" an update to a zip it looks like it only affects things you extract. I don't think `os.rename` works, `os.rename("zipfile.zip/file", "zipfile.zip/file2")` certainly doesn't. – user12859943 Jan 29 '21 at 17:56