Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a zip file with compression in python using the zipfile module

I am new to python. My requirement is to zip (with compression) all files from a source directory to a target directory. I have used following code from stackOverFlow.

import zipfile, os
locfile = "D:\Python\Dir_dir\Dir_dir\ABC.txt"
loczip = "D:\Python\Dir_dir\Dir_dir2\ABC_TEST.zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()

It is creating a zip file but it contains the entire inherited directory structure. Except the drive(D:/) the rest of the structure is added to zip. It looks like the following: "D:\Python\Dir_dir\Dir_dir2\ABC_TEST.zip\Python\Dir_dir\Dir_dir\ABC.txt"

whereas i wanted: "D:\Python\Dir_dir\Dir_dir2\ABC_TEST.zip\ABC.txt"

Also it is not compressed.

like image 209
user2285058 Avatar asked Dec 12 '22 03:12

user2285058


2 Answers

To enable compression, specify compression method in the constructor:

zip = zipfile.ZipFile(loczip, "w", zipfile.ZIP_DEFLATED)

I think you are asking to remove the relative paths of files inside the zip file. If you really want that, you could write:

zip.write(locfile, os.path.basename(locfile))

However this is probably a bad idea, since removing all path information would result in a naming conflict if you zip up two files with the same name.

like image 162
snowcrash09 Avatar answered Jan 19 '23 00:01

snowcrash09


Check the official documentation and it addresses your issues clearly.

ZipFile.write(filename, arcname=None, compress_type=None)

compress should be one of the defined constants, e.g., ZIP_DEFLATED

Note that you can also specifcy the conmpression type on the constructor and it will apply to all files added to the zip archive.

The documentation also includes this note: Archive names should be relative to the archive root, that is, they should not start with a path separator.

Also if you had simply entered python zipfile into any search engine, you would have seen the official documentation as one of the first links.

like image 23
Gary Walker Avatar answered Jan 19 '23 00:01

Gary Walker