joe wong joe wong -4 years ago 244
Python Question

Python 2.6 - Add a file to zipfile without folders

6 to work on zipfiles.

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?

Thanks in advance.

Answer Source

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', ...]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download