Simple tutorial for compressing files using the gzip module in Python-Python tutorial

Source: Internet
Author: User
This article describes how to use the gzip module to compress files in Python. the examples in this article are mainly for UNIXZ systems. For more information, see Create a gzip file with compressed data
First look at a slightly troublesome practice

Import StringIO, gzipcontent = 'Life is short. I use python 'zbuf = StringIO. stringIO () zfile = gzip. gzipFile (mode = 'WB ', compresslevel = 9, fileobj = zbuf) zfile. write (content) zfile. close ()

However, there is a fast encapsulation, and the StringIO module is not used.

F = gzip.open('file.gz ', 'wb') f. write (content) f. close ()

Compress existing files
After python2.7, you can use the with statement.

Import gzipwith open ("/path/to/file", 'RB') as plain_file: with gzip. open ("/path/to/file.gz", 'wb') as zip_file: zip_file.writelines (plain_file)

If you do not consider cross-platform, only on the linux platform, the following method is more direct:

From subprocess import check_callcheck_call ('gzip/path/to/file', shell = True)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.