Python csv 文件中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27504056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Row count in a csv file
提问by Dirty_Fox
I am probably making a stupid mistake, but I can't find where it is. I want to count the number of lines in my csv file. I wrote this, and obviously isn't working: I have row_count = 0while it should be 400. Cheers.
我可能犯了一个愚蠢的错误,但我找不到它在哪里。我想计算我的 csv 文件中的行数。我写了这个,显然不起作用:我有,row_count = 0而它应该是 400。干杯。
f = open(adresse,"r")
reader = csv.reader(f,delimiter = ",")
data = [l for l in reader]
row_count = sum(1 for row in reader)
print row_count
采纳答案by jamylak
with open(adresse,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
You are trying to read the file twice, when the file pointer has already reached the end of file after saving the datalist.
当保存data列表后文件指针已到达文件末尾时,您正尝试读取文件两次。
回答by protti
First you have to open the file with open
首先,您必须使用 open 打开文件
input_file = open("nameOfFile.csv","r+")
Then use the csv.reader for open the csv
然后使用 csv.reader 打开 csv
reader_file = csv.reader(input_file)
At the last, you can take the number of row with the instruction 'len'
最后,您可以使用指令“len”获取行数
value = len(list(reader_file))
The total code is this:
总代码是这样的:
input_file = open("nameOfFile.csv","r+")
reader_file = csv.reader(input_file)
value = len(list(reader_file))
Remember that if you want to reuse the csv file, you have to make a input_file.fseek(0), because when you use a list for the reader_file, it reads all file, and the pointer in the file change its position
记住,如果你想重用csv文件,你必须做一个input_file.fseek(0),因为当你使用reader_file的列表时,它读取所有文件,文件中的指针改变了它的位置
回答by Hari Prasanna Addanki
If you are working with python3 and have pandas library installed you can go with
如果您正在使用 python3 并安装了 pandas 库,则可以使用
import pandas as pd
results = pd.read_csv('f.csv')
print(len(results))
回答by Murali K Thota
# with built in libraries
opened_file = open('f.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
rowcount = len(apps_data) #which incudes header row
print("Total rows incuding header: " + str(rowcount))
回答by user12838023
Simply Open the csv file in Notepad++. It shows the total row count in a jiffy. :) Or in cmd prompt , Provide file path and key in the command find \c \v "some meaningless string" Filename.csv
只需在 Notepad++ 中打开 csv 文件。它立即显示总行数。:) 或者在 cmd 提示符下,提供文件路径并在命令中键入 find \c \v "somemeanless string" Filename.csv

