【发布时间】:2014-04-15 18:37:49
【问题描述】:
我必须使用 python 2.7,因为我使用的是 boto 库,而 boto3 是实验性的。我需要读取一个压缩过的文件,并且行由回车终止。使用python 3.3 似乎你可以在gzip.open 中指定换行变量。在 python 2.7 中,最干净且仍然有效的方法是什么。
【问题讨论】:
标签: python python-2.7 gzip
我必须使用 python 2.7,因为我使用的是 boto 库,而 boto3 是实验性的。我需要读取一个压缩过的文件,并且行由回车终止。使用python 3.3 似乎你可以在gzip.open 中指定换行变量。在 python 2.7 中,最干净且仍然有效的方法是什么。
【问题讨论】:
标签: python python-2.7 gzip
您可以尝试使用io 模块将 gzip 压缩文件作为文本逐行读取,并支持通用换行符:
import gzip
import io
with io.TextIOWrapper(io.BufferedReader(gzip.open(filename))) as file:
for line in file:
print line,
【讨论】:
BufferedReader 包裹GzipFile 是真正使这项工作有效的原因!非常感谢,我一直在试图让readlines() 只为TextIOWrapper 工作!