How to Compress Files with Python

In this article we want to learn How to Compress Files with Python, Python is popular and powerful programming language and it offers different libraries to make coding easier and more efficient. gzip is a library that we can use for compressing and decompressing of files. file compression is the process of reducing size of a file by encoding its data in more efficient way. compressed files are easier to store, transfer and use. in this article we want to talk that how to compress and decompress files using Python gzip module.

 

 

What is gzip module ?

gzip module is builtin module in Python that provides simple and efficient way to compress and decompress files. this module uses GZIP file format, and it is widely used file format for file compression. GZIP file format is based on the DEFLATE algorithm, and it is lossless data compression algorithm that works by replacing repeated occurrences of data with references to single copy of that data.

 

 

For compressing a file using gzip module, first we need to import the module using this command.

 

After that we can use gzip.open() method to open the file that we want to compress, also we specify the mode of comress, in this case that is wb.

 

 

This is an example of how to compress a file at name of file.txt using gzip module, in this example, first of all we open our file.txt in read binary mode using open() function. after that we use gzip.open() function for creating a new file called file.txt.gz and open it in write binary mode, and lastly we use writelines() method to write the contents of the original file to the compressed file. contents are compressed using GZIP algorithm, and the resulting file has .gz file extension.

 

 

We have learned about compressing a file using Python, now let’s talk about decompressing of a file using Python, for decompressing a file using gzip module, first we need to import the library.

 

 

After that we can use gzip.open() method to open the compressed file, also we need to specify decompress file mode, in our case it is rb.

 

 

This is an example of how to decompress a file called file.txt.gz using the gzip module:

 

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×