I am trying to zip a single file in python. For whatever reason, I'm having a hard time getting down the syntax. What I am trying to do is keep the original file and create a new zipped file of the original (like what a Mac or Windows would do if you archive a file).
Here is what I have so far:
import zipfile myfilepath = '/tmp/%s' % self.file_name myzippath = myfilepath.replace('.xml', '.zip') zipfile.ZipFile(myzippath, 'w').write(open(myfilepath).read()) # does not zip the file properly
If the file to be zipped (
filename) is in a different directory called
pathname, you should use the
arcname parameter. Otherwise, it will recreate the full folder hierarchy to the file folder.
from zipfile import ZipFile import os with ZipFile(zip_file, 'w') as zipf: zipf.write(os.path.join(pathname,filename), arcname=filename)
The correct way to zip file is:
zipfile.ZipFile('hello.zip', mode='w').write("hello.csv") # assume your xxx.py under the same dir with hello.csv
The python official doc says:
ZipFile.write(filename, arcname=None, compress_type=None)
Write the file named filename to the archive, giving it the archive name arcname
open(filename).read() is a single string that contains the whole content of file
filename, it would throw
FileNotFoundError because it is trying to find a file named with the string content.