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