Python 从压缩文件中读取 csv 行

Python read csv line from gzipped file

我正在尝试解析一个 gzip 压缩的 csv 文件(其中字段由 | 字符分隔),以测试直接在 Python 中读取文件是否比 zcat file.gz | python 解析内容。

我有以下代码:

#!/usr/bin/python3

import gzip

if __name__ == "__main__": 
    total=0
    count=0

    f=gzip.open('SmallData.DAT.gz', 'r')
    for line in f.readlines():
        split_line = line.split('|')
        total += int(split_line[52])
        count += 1

    print(count, " :: ", total)

但是我得到以下错误:

$ ./PyZip.py 
Traceback (most recent call last):
  File "./PyZip.py", line 11, in <module>
    split_line = line.split('|')
TypeError: a bytes-like object is required, not 'str'

如何修改它以读取该行并将其正确拆分?

我主要对由 | 分隔的第 52 个字段感兴趣。我的输入文件中的行如下所示:

字段 1|字段 2|字段 3|...字段 52|字段 53

有没有比我对第 52 个字段中的所有值求和更快的方法?

谢谢!

您应该在拆分之前先解码该行,因为解压缩的文件是按字节读取的:

split_line = line.decode('utf-8').split('|')

用于对第 52 个字段中的所有值求和的代码没有问题。没有办法让它更快,因为所有的行都必须被读取和拆分才能识别每行的第 52 个字段。

尝试将字节对象解码为字符串。即

line.decode('utf-8')

更新脚本:

#!/usr/bin/python3
import gzip

if __name__ == "__main__": 
    total=0
    count=0

    f=gzip.open('SmallData.DAT.gz', 'r')
    for line in f.readlines():
        split_line = line.decode("utf-8").split('|')
         total += int(split_line[52])
         count += 1

    print(count, " :: ", total)