'how to create zip file on a absolute path using zipfile
I am trying to create a zip file of files from different directories. At the end, I want to save that zip file to a different path than python file python. I have the following code snippet
def zipfile_method(file_list):
try:
zip_path = os.path.abspath('/Users/nirmalsarswat/Document/jdk.zip')
print(zip_path)
zip_file = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
for files in file_list:
path = os.path.abspath(files)
zip_file.write(path)
zip_file.close()
except Exception as e:
print("exception occured during compression %s" % e)
zipfile_method(['/Users/nirmalsarswat/Desktop/jdk-8u171-macosx-x64.dmg', '/Users/nirmalsarswat/Desktop/resume-nirmal-sarswat.pdf'])
Path of my python file is /Users/nirmalsarswat/Desktop/app.py
.
I expect that file path would be on /Users/nirmalsarswat/Document/jdk.zip
but zipfile saves it on the same folder of python file like this /Users/nirmalsarswat/Desktop/Users/nirmalsarswat/Document/jdk.zip
.
How I can make to save the file on /Users/nirmalsarswat/Document/jdk.zip
path
I am using MacOS, Python 3.6.4.
Solution 1:[1]
Actually what I can see is, you are doing correct but you are confused with paths. When you pass the only absolute path to write
, it will zip the file with a complete directory which seems the problem you are facing.
Try parsing basename
with write
and it will work fine, like this
from os.path import basename # add this to your imports
def zipfile_method(file_list):
try:
zip_path = os.path.abspath('/Users/nirmalsarswat/Document/jdk.zip') # no need to this one, parse string itself
print(zip_path)
zip_file = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
for files in file_list:
path = os.path.abspath(files)
zip_file.write(path, basename(path))
zip_file.close()
except Exception as e:
print("exception occured during compression %s" % e)
zipfile_method(['/Users/nirmalsarswat/Desktop/jdk-8u171-macosx-x64.dmg', '/Users/nirmalsarswat/Desktop/resume-nirmal-sarswat.pdf'])
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 | LAMRIN TAWSRAS |