Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zip file and avoid directory structure

Tags:

python

zip

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 
like image 547
user1189851 Avatar asked Jan 16 '15 19:01

user1189851


People also ask

How do I zip a file without path?

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.

Can you zip a file with subfolders?

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

What is a zip directory?

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.


1 Answers

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") 
like image 86
user 12321 Avatar answered Sep 19 '22 06:09

user 12321