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
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With