从 python 中的 gzip 文件读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12902540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read from a gzip file in python
提问by Michael
I've just make excises of gzip on python.
我刚刚在 python 上删除了 gzip。
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
And I get no output on the screen. As a beginner of python, I'm wondering what should I do if I want to read the content of the file in the gzip file. Thank you.
我在屏幕上没有输出。作为python的初学者,我想知道如果我想读取gzip文件中的文件内容应该怎么做。谢谢你。
采纳答案by Matt Olan
Try gzipping some data through the gzip libary like this...
尝试像这样通过 gzip 库压缩一些数据......
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.
这种方法对我有用,因为由于某种原因 gzip 库无法读取某些文件。
回答by Arunava Ghosh
python: read lines from compressed text files
Using gzip.GzipFile:
使用gzip.GzipFile:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)

