拆分csv文件的分隔符在Python中不起作用

时间:2015-12-07 20:33:33

标签: python sorting csv

我有一个csv文件,其条目如下:

00020000001000,gl3.h5,2,5,0,0,0,"1:15:29 PM",60.2350934,-138.29382304 etc.
00020010000000,gl3.h5,2,8,0,0,0,"1:16:24 PM",60.09523934,-138.2322304 etc.
00020000100000,gl3.h5,2,11,0,0,0,"1:17:05 PM",60.0345934,-138.2932582304 etc.
00020000000100,gl3.h5,2,4,0,0,0,"1:18:19 PM",60.090934,-138.2235382304 etc.

现在,我想按第3列中的整数对此文件中的行进行排序(例如,第一行中为5,第二行中为8

到目前为止我的代码看起来像:

import csv
with open("line 1.csv", "rb") as f:
    reader = csv.reader(f, delimiter = ",")
    sort = sorted(reader, key=lambda x: int(x[3]), reverse=True)
    print(sort)

但是当我运行代码时,它会显示IndexError: list index out of range"

为什么分隔符,不起作用?

谢谢!

1 个答案:

答案 0 :(得分:0)

你的csv中可能有空行。过滤掉它们:

import csv
with open("line 1.csv", "rb") as f:
    reader = csv.reader(f, delimiter = ",")
    data = [entry for entry in reader if entry]
    sort = sorted(data, key=lambda x: int(x[3]), reverse=True)
    print(sort)