• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

55
Views
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
3 months ago ·

Santiago Trujillo

3 answers
Answer question

0

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)
3 months ago · Santiago Trujillo Report

0

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.

3 months ago · Santiago Trujillo Report

0

Try calling zipfile.close() afterwards?

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

   zipf.close()
3 months ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.