'Append a file to a ZipFile in python

First I created a new zipfile:

import zipfile
zf = zipfile.ZipFile('/data2/new.zip', mode='w')

then I wanted to append a file into the newly created zipfile, say download.py in another folder:

zf.write('/data2/another_folder/download.py')

All seemed fine until I unzip it locally and I found that it did not just append the file, but also append all the folders, data2 and another_folder. I have to open /data2/new/data2/another_folder/ to find download.py.

I want to append and only append the file to zipfile. How can I avoid the aforementioned situation?



Solution 1:[1]

The zipfile.write() method takes an optional arcname argument that specifies what the name of the file should be inside the zipfile.

import os
import zipfile


zf.write('/data2/another_folder/download.py', 'download.py')
zf.close()

Here's a function to zip multiple files together:

def zip(list_of_file_paths):
   zf = zipfile.ZipFile("Zipfile.zip", "w", zipfile.ZIP_DEFLATED)
   for path in list_of_file_paths:
       filename = os.path.basename(os.path.normpath(path))
       zf.write(path, filename)
   zf.close()

zip(['path/to/file1', 'path/to/file2', ...]

Solution 2:[2]

zf.write('path/to/file.txt', arcname='name_without_path.txt')

should solve that for you, if you want to keep the same name without the path you can also do this:

filepath = 'path/to/file.txt'
zf.write(filepath, arcname=os.path.basename(filepath))

that assumes you did import os of course

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cs95
Solution 2 Ofer Sadan