简体   繁体   中英

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.

Please anyone share the solution for this problem.

Thanks, Subrat

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.

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, eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM