Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip single file

Tags:

python

zip

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
like image 544
David542 Avatar asked Feb 13 '17 22:02

David542


People also ask

How do I zip individual files?

Right-click on the file or folder.Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I zip a single file in Linux?

The easiest way to zip a folder on Linux is to use the “zip” command with the “-r” option and specify the file of your archive as well as the folders to be added to your zip file. You can also specify multiple folders if you want to have multiple directories compressed in your zip file.


4 Answers

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)
like image 119
nbeuchat Avatar answered Oct 05 '22 21:10

nbeuchat


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.

like image 41
Haifeng Zhang Avatar answered Oct 05 '22 20:10

Haifeng Zhang


Try calling zipfile.close() afterwards?

   from zipfile import ZipFile
   zipf = ZipFile("main.zip","w", zipfile.ZIP_DEFLATED)
   zipf.write("main.json")

   zipf.close()
like image 44
ndsilva Avatar answered Oct 05 '22 22:10

ndsilva


Since you also want to specify the directory try using os.chdir:

#!/usr/bin/python

from zipfile import ZipFile
import os

os.chdir('/path/of/target/and/destination')
ZipFile('archive.zip', 'w').write('original_file.txt')
  • Python zipfile : Work with Zip archives
  • Python Miscellaneous operating system interfaces
like image 39
l'L'l Avatar answered Oct 05 '22 22:10

l'L'l