1

How would I add the contents of an entire directory to an already existing zip file using python? The directory to be added to the zip file will also include other folders as well and there will be duplicates in the zip file that will need to be overwritten. Any help would be appreciated. Thanks in advance!

P.S. If it is possible to zip the directory then combine both files that would also work.

ThatGuyJay
  • 307
  • 2
  • 5
  • 13

1 Answers1

2

Python's zipfile module allows you to manipular ZIP compressed archives. The ZipFile.namelist() method returns a list of files in an archive, and the ZipFile.write() method lets you add files to the archive.

z = zipfile.ZipFile('myfile.zip')

The os.walk method allows you to iterate over all the files contained in a directory tree.

for root, dirs, files in os.walk('mydir'):
  for filename in files:
    z.write(os.path.join(root, filename))

Replacing a file in an archive appears to be tricky; you can removed items by creating a temporary archive and then replacing the original when you're done as described in this question.

It might be easier just to call the zip command instead, but put these together and you should be able to get to where you want.

Community
  • 1
  • 1
larsks
  • 277,717
  • 41
  • 399
  • 399