【问题标题】:Python read csv line from gzipped filePython 从 gzip 文件中读取 csv 行
【发布时间】:2018-08-01 03:01:44
【问题描述】:

我正在尝试解析一个 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 个字段感兴趣。我的输入文件中的行如下:

field1|field2|field3|...field52|field53

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

谢谢!

【问题讨论】:

    标签: python csv gzip


    【解决方案1】:

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

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

    用于对第 52 个字段中的所有值求和的代码很好。没有办法让它更快,因为只需要读取和拆分所有行才能识别每行的第 52 个字段。

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2012-10-05
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 2018-01-08
        相关资源
        最近更新 更多