簡體   English   中英

Python從gzip壓縮文件中讀取csv行

[英]Python read csv line from gzipped file

我正在嘗試解析gzip壓縮的csv文件(其中的字段由|字符分隔),以測試是否直接在Python中讀取文件是否比zcat file.gz | python更快zcat file.gz | 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 |科研成果|場3 | ... field52 | field53

是否有比我將第52個字段中的所有值求和的方法更快的方法?

謝謝!

您應該先對行進行解碼,然后再進行拆分,因為解壓縮后的文件將以字節讀取:

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

您將第52個字段中的所有值相加的代碼很好。 沒有辦法使其更快,因為僅需讀取和拆分所有行即可識別每行的第52個字段。

只需嘗試將bytes對象解碼為字符串即可。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM