Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
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
over 4 years 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)
over 4 years 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.

over 4 years 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()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!