Python Read Gzip File: Complete Guide
To read a gzip file, you can use the gzip module. Here is an example code:
import gzip
# 打开gzip文件
with gzip.open('file.gz', 'rb') as f:
# 读取gzip文件内容
content = f.read()
# 将gzip文件内容解压缩
content = gzip.decompress(content)
# 打印解压后的内容
print(content)
In the code above, the gzip file is first opened using the gzip.open() function. The first parameter is the path to the gzip file, and the second parameter is the mode to open the file. The ‘rb’ mode indicates that the file is being read in binary mode.
Then, use the .read() method to read the contents of the gzip file. This will return the compressed binary data.
Next, use the gzip.decompress() function to decompress the compressed binary data and obtain the original content.
Finally, you can print the extracted content or do other processing.