从 python 中的 gzip 文件读取

我刚刚在 python 上做了 gzip 的练习。

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

屏幕上没有输出。作为 python 的初学者,我想知道如果我想读取 gzip 文件中的文件内容,我应该怎么做。谢谢你。

204057 次浏览

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip


with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)

for parquet file, pls using pandas to read

data = read_parquet("file.parquet.gzip")
data.head()

If you want to read the contents to a string, then open the file in text mode (mode="rt")

import gzip


with gzip.open("Onlyfinnaly.log.gz", mode="rt") as f:
file_content = f.read()
print(file_content)