我如何获得'行的数量'在CSV文件中。这是我尝试过的:
reader = csv.DictReader(open(filepath), delimiter='|')
print len(reader)
AttributeError: DictReader instance has no attribute '__len__'
答案 0 :(得分:2)
你可以sum
使用一个生成器表达式,每行的len而不是将每个都读入列表中,如果你只想计算总元素:
reader = csv.reader(open(filepath), delimiter='|')
print(sum(len(row) for row in reader))
或者只是打开并拆分:
with open(filepath) as f:
print(sum(len(line.split("|")) for line in f))
如果您想要实际行数:
with open(filepath) as f:
print(sum(1 for _ in f))
答案 1 :(得分:1)
试试这个:
rows = list(reader)
totalrows = len(rows)