Search code examples
pythonzip

Zip single file


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

Solution

  • 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

    You pass open(filename).read() into write(). 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.