zip file and avoid directory structure

user1189851 picture user1189851 · Jan 16, 2015 · Viewed 36.1k times · Source

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

Answer

user 12321 picture user 12321 · Jan 16, 2015

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")