如何获取CSV文件的行数? [英] How can I get the row count of a CSV file?

查看:1954
本文介绍了如何获取CSV文件的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fieldnames = ['first_name', 'last_name', 'address']
with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    for row in reader:
        print(row['first_name'], "'s number", row['last_name'], "address", row['adres'])

这是我的代码,用于打印CSV文件.如果CSV文件为空,我想打印为空.我以为如果可以获取文件的行数,就可以检查文件是否为空.

This is my code to print my CSV file. If the CSV file is empty, I want to print that it's empty. I thought that if i can get the row count of the file, I can check if it's empty.

推荐答案

做到这一点

len(list(reader))

遍历reader对象以创建列表,然后计算长度&数字或行数是列表长度(不包括标题)

it iterates through the reader object to create a list, then computes length & the number or rows is the list length (title not included)

请注意,此语句消耗了文件,因此,如果您打算解析文件,请在某个位置存储list(reader)变量.

note that this statement consumes the file, so store the list(reader) variable somewhere if you plan to parse the file.

这篇关于如何获取CSV文件的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆