Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I zip file with a flattened directory structure using Zipfile in Python?

I'm using the ZipFile package to zip file in Python. Here's my code:

archive = zipfile.ZipFile(join(settings.ARCHIVES_DIR, 'test.zip'), "a")

for pdffile in glob.glob(join(settings.IBILLING_DIR, '*.pdf')):
    archive.write(pdffile)

archive.close()

The issue I'm facing is that the ZIP file that is created, contains a directory structure. The files that are added are added with the full the path which means that the user that extracts the archive, will also end up getting a directory structure. I'd like to the add files to the ZIP but without any directory structure.

How can I do this? I didn't find this information in the docs.

Thanks

like image 896
Mridang Agarwalla Avatar asked Oct 08 '12 07:10

Mridang Agarwalla


People also ask

How do I zip a file in ZipFile Python?

To compress individual files into a ZIP file, create a new ZipFile object and add the files you want to compress with the write() method. With zipfile. ZipFile() , specify the path of a newly created ZIP file as the first parameter file , and set the second parameter mode to 'w' (write).

Which statement successfully creates a zip file using the ZipFile module in Python?

with ZipFile(file_name, 'r') as zip: Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip.

What does ZipFile ZipFile do?

The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.

How do I unzip a ZipFile module in Python?

Import the zipfile module Create a zip file object using ZipFile class. Call the extract() method on the zip file object and pass the name of the file to be extracted and the path where the file needed to be extracted and Extracting the specific file present in the zip.


1 Answers

First add

import os

then modify the archive.write line to be:

archive.write(pdffile, os.path.basename(pdffile))

This specifies that each pdf should be written into the zip file with a path equivalent to only the filename portion of the path from which you are reading it (by specifying the arcname parameter for the write() call).

Note, however, that this means that if you have two PDF files with the same name in different directories, one will overwrite the other.

like image 149
Amber Avatar answered Oct 07 '22 03:10

Amber