How to read gzip files in Python?

To read a gzip file, you can utilize the gzip module in Python. Below is an example code for reading a gzip file.

import gzip

# 打开gzip文件
with gzip.open('file.gz', 'rb') as f:
    # 读取文件内容
    content = f.read()

# 打印文件内容
print(content)

In the example above, the gzip file is first opened using the gzip.open() function, which takes the file name and the open mode (‘rb’ indicating reading the file in binary mode). After that, the content of the file is read using the read() method, and finally the file content is printed.

Please note that if the file in a gzip archive contains text content, you can use the decode() method to convert the byte stream into a string. For example:

import gzip

with gzip.open('file.gz', 'rb') as f:
    content = f.read().decode('utf-8')

print(content)

After reading the file content, the above code decodes the byte stream into a UTF-8 encoded string using the decode(‘utf-8’) method.

bannerAds