【问题标题】:How do you iterate through a gzipped carriage-return file using python 2.7?如何使用 python 2.7 遍历 gzip 后的回车文件?
【发布时间】:2014-04-15 18:37:49
【问题描述】:

我必须使用 python 2.7,因为我使用的是 boto 库,而 boto3 是实验性的。我需要读取一个压缩过的文件,并且行由回车终止。使用python 3.3 似乎你可以在gzip.open 中指定换行变量。在 python 2.7 中,最干净且仍然有效的方法是什么。

【问题讨论】:

    标签: python python-2.7 gzip


    【解决方案1】:

    您可以尝试使用io 模块将 gzip 压缩文件作为文本逐行读取,并支持通用换行符:

    import gzip
    import io
    
    with io.TextIOWrapper(io.BufferedReader(gzip.open(filename))) as file:
        for line in file:
            print line,
    

    【讨论】:

    • io.TextIOWrapper(io.BufferedReader(gzip.open(filePath)), encoding='utf8', errors='ignore') 甚至支持编码和错误处理。谢谢!
    • BufferedReader 包裹GzipFile 是真正使这项工作有效的原因!非常感谢,我一直在试图让readlines() 只为TextIOWrapper 工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多