3

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!

Almog
  • 452
  • 1
  • 7
  • 13
j. doe
  • 163
  • 3
  • 11
  • 1
    Does this answer your question? [Delete file from zipfile with the ZipFile Module](https://stackoverflow.com/questions/513788/delete-file-from-zipfile-with-the-zipfile-module) – shreyasm-dev Aug 12 '20 at 23:43

2 Answers2

0

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.

Aaron Bentley
  • 1,332
  • 8
  • 14
-1

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)
  • Thank you for your response! If I'm understanding correctly, is the code removing the files from the .zip file that are in the "files" list and storing them in a new location? – j. doe Aug 12 '20 at 23:56
  • Yes, it extracts the files `1.txt`, `2.txt`, `3.txt` from the folder `path-to-file` which is inside `my-file.zip` (the zip file). – BerkZerker707 Aug 14 '20 at 17:44
  • 1
    can i just directly delete it without saving it at another location? – j. doe Aug 15 '20 at 22:54
  • how do I permanently delete the files that don't match the items in file_list? – j. doe Aug 16 '20 at 00:04
  • You can move all the files that you don't want out and delete them normally. Just make it move the file if it's not in your list. – BerkZerker707 Aug 16 '20 at 23:03
  • 1
    It does not delete file in the archive. Please clarify how you managed to do that? – Kyrylo Kravets Sep 08 '21 at 15:02