'zipfile writing .zip output to .py file location
The following script is writing a zip into the directory where the .py file is located, but I need it to write it to the same location as the original folder.
I am suspecting it has something to do with the functionality of the zipfile.ZipFile object, but I can't seem to resolve the issue. Any help would be greatly appreciated! Thank you!
import sys, zipfile, os, traceback, Tkinter, tkFileDialog
def zipws(path, zip, keep):
path = os.path.normpath(path)
print("Zipping {}...".format(path))
for (dirpath, dirnames, filenames) in os.walk(path):
for file in filenames:
if not file.endswith('.lock'):
try:
if keep:
zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):]))
else:
zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file))
except Exception, e:
print(" Error adding {}: {}".format(file, e))
return None
try:
root = Tkinter.Tk()
root.withdraw()
root.attributes('-topmost', True)
getGDBLoc = tkFileDialog.askdirectory(parent=root, initialdir="C:", title='Select the folder which contains the GDBs to be zipped')
root.attributes('-topmost', False)
wkPath = os.path.abspath(getGDBLoc).replace("\\","/")
root.destroy()
for fldr in os.listdir(wkPath):
if fldr.endswith('.gdb'):
outfile = fldr+".zip"
try:
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
zipws(os.path.join(wkPath,fldr), zip, False)
zip.close()
print(" >> {} zipped successfully".format(outfile))
except RuntimeError:
if os.path.exists(outfile):
os.unlink(outfile)
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
zipws(os.path.join(wkPath,fldr), zip, False)
zip.close()
print(" >> {} zipped, however unable to compress zip file contents.".format(outfile))
except:
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
print("PYTHON ERRORS:\nTraceback Info:\n{}\nError Info:\n {}: {}\n".format(tbinfo, sys.exc_type, sys.exc_value))
Solution 1:[1]
Found the error. As expected, my problem was when I created the zipfile.ZipFile object. Outfile needed to be a full path location, not just output file name.
Changed these lines:
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
To this:
zip = zipfile.ZipFile(os.path.join(wkPath,outfile), 'w', zipfile.ZIP_DEFLATED)
I swear I tried this before and it didn't work, but it is working now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MCline |