How to use the gzip module for file compression and decompression in Python 3.x
Introduction:
In daily development, we often need to compress and decompress files. The gzip module in Python provides a convenient and concise API to perform gzip compression and decompression operations when processing files. This article will introduce how to use the gzip module to compress and decompress files, and give corresponding code examples.
import gzip def compress_file(filename, compressed_filename): with open(filename, 'rb') as f_in, gzip.open(compressed_filename, 'wb') as f_out: f_out.writelines(f_in) print("File compressed successfully!") if __name__ == '__main__': compress_file("example.txt", "example.txt.gz")
In the above code, we first use the open function to open the file that needs to be compressed, and read the file content in binary mode ('rb'). Then, use the gzip.open function to create a GzipFile object and write the compressed file contents in binary mode ('wb').
import gzip def decompress_file(compressed_filename, filename): with gzip.open(compressed_filename, 'rb') as f_in, open(filename, 'wb') as f_out: f_out.writelines(f_in) print("File decompressed successfully!") if __name__ == '__main__': decompress_file("example.txt.gz", "example.txt")
In the above code, we first use the gzip.open function to open the file that needs to be decompressed, and read the compressed file in binary mode ('rb') content. Then, use the open function to create a file object and write the decompressed file contents in binary mode ('wb').
Conclusion:
This article introduces how to use the gzip module in Python 3.x to perform file compression and decompression operations. Through the compression and decompression methods provided by the GzipFile class, we can conveniently manipulate file contents. The usage of the gzip module is simple and clear, which can save time and energy in daily development. I hope readers can understand and flexibly use the gzip module through this article.
The above is the detailed content of How to use the gzip module for file compression and decompression in Python 3.x. For more information, please follow other related articles on the PHP Chinese website!