Is it possible to delete files in a .zip file without unzipping it Python?

Viewed 3553

I have a .zip file with around 26k image files. I have a list of files that I want to keep in the .zip

I was wondering if it was possible for me to remove files within that .zip that aren't in my file list without unzipping the actual folder (because it would take up way too much space on my computer) using Python 3.

I couldn't find anything on this and was wondering if anyone knows a way I can do this

Thank you!

2 Answers

You can use zipfile. It is included in python. Here's an example, where I extract 3 files from my-file.zip.

import zipfile

files = ['1.txt', '2.txt', '3.txt']

with zipfile.ZipFile('my-file.zip', 'r') as file:
    for f in files:
        file.extract('path-to-file/' + f)

Python's standard library doesn't support altering an existing zip archive, and I don't see any likely candidates in PyPI.

The zip utility can delete files from an archive (-d), so you may be able to script it instead, perhaps using Python.

Another option would be to create a new zip archive based on the existing one, and skip the files you don't want. That would not require extracting any files to disk, but it could be CPU-intensive.

Related