I have a Python script that zips a file (new.txt
):
tofile = "/root/files/result/"+file targetzipfile = new.zip # This is how I want my zip to look like zf = zipfile.ZipFile(targetzipfile, mode='w') try: #adding to archive zf.write(tofile) finally: zf.close()
When I do this I get the zip file. But when I try to unzip the file I get the text file inside of a series of directories corresponding to the path of the file i.e I see a folder called root
in the result
directory and more directories within it, i.e. I have
/root/files/result/new.zip
and when I unzip new.zip
I have a directory structure that looks like
/root/files/result/root/files/result/new.txt
Is there a way I can zip such that when I unzip I only get new.txt
?
In other words I have /root/files/result/new.zip
and when I unzip new.zip
, it should look like
/root/files/results/new.txt
Use the -j option with zip . -j is "junk the path". According to the man page on zip: Store just the name of a saved file (junk the path), and do not store directory names.
On the General tab in Properties, click the button Advanced. In the next window, tick the check box Compress contents to save disk space under the Compress or Encrypt attributes section. There, you need to choose "Apply changes to this folder only" or "Apply changes to this folder, subfolders and files".
ZIP files work in much the same way as a standard folder on your computer. They contain data and files together in one place. But with zipped files, the contents are compressed, which reduces the amount of data used by your computer. Another way to describe ZIP files is as an archive.
The zipfile.write()
method takes an optional arcname
argument that specifies what the name of the file should be inside the zipfile
I think you need to do a modification for the destination, otherwise it will duplicate the directory. Use :arcname
to avoid it. try like this:
import os import zipfile def zip(src, dst): zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED) abs_src = os.path.abspath(src) for dirname, subdirs, files in os.walk(src): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) zf.close() zip("src", "dst")
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