Wednesday, March 16, 2011

With Python, how can I ensure that compression of a folder takes place within a particular folder?

I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance.

clarification of question with code example:

Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive.


def zip_folder(basedir, zip_file): z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(basedir): print "zipping files:" for fn in filenames: print fn absfn = os.path.join(dirpath, fn) z.write(absfn) z.close

From stackoverflow
  • Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path.

0 comments:

Post a Comment