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/', mode='w')

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


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,
. I have to open
to find

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/', '')

Here's a function to zip multiple files together:

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

zip(['path/to/file1', 'path/to/file2', ...]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download