我有一个csv文件,如下面的
,0,1,2,3,4,5,6,7,8,9,10,11,12
0,7498.0,7499.0,,,,,,,,,,
1,7445.0,7456.0,,,,,,,,,,
2,7412.0,7413.0,7414.0,,,,,,,,,
3,7338.0,7412.0,7413.0,7414.0,,,,,,,,
4,7261.0,7021.0,,,,,,,,,,
我需要得到每条线的长度,如下所示。如何用python做到这一点?
2
2
3
4
2
这不起作用,因为它计算所有行分割。
f = open('myfile','r')
lines = f.readlines()
for line in lines:
li = line.split(',')
print len(li)
答案 0 :(得分:5)
您显然想要计算非空列。
首先,使用csv
module;无需重新发明CSV读取轮。然后筛选出空列并计算:
import csv
with open('myfile', 'rb') as f:
reader = csv.reader(f)
for row in reader:
# count non-empty cells, but ignore the first
nonempty = [cell for cell in row[1:] if cell]
print len(nonempty)
答案 1 :(得分:0)
答案 2 :(得分:0)
with open("myfile") as i:
reader = csv.reader(i)
for line in reader:
print(len([x for x in line if x != ""]))
输出:
13
3
3
4
5
3