with open("C:/Users/number-UK.csv") as csvfile:
# read csv
readCSV = csv.reader(csvfile, delimiter=',')
# print the number of items/rows in the csv file
print("Step 2: Confirm the total numbers:",int(len(list(readCSV)))-1)
continue_text = input("Enter anything to continue")
# skip the headers
next(readCSV, None)
i=0
for each_user in readCSV:
print(i+1," item:",str(each_user[0]))
i = i + 1
print("all done!")
上面的代码不起作用。当我删除下面的行时,代码就可以工作了。
print("Step 2: Confirm the total numbers:",int(len(list(readCSV)))-1)
我想在for循环之前计算csv文件的行数,有人知道如何实现这一点吗?非常感谢。
问题是“list(readCSV)”耗尽了读者的精力,因此您的后续调用不再有任何元素。
两种补救方法。
选项 1(使用列表而不是生成器进行 readCSV)
with open("C:/Users/number-UK.csv") as csvfile:
# read csv (using list rather than iterator)
readCSV = list(csv.reader(csvfile, delimiter=','))
# print the number of items/rows in the csv file
print("Step 2: Confirm the total numbers:",int(len(readCSV))-1)
continue_text = input("Enter anything to continue")
# skip the headers
#next(readCSV, None) # not used
i=0
for each_user in readCSV[1:]: # start at 1 to skip header
print(i+1," item:",str(each_user[0]))
i = i + 1
print("all done!")
选项2(重新获取readCSV)
with open("C:/Users/number-UK.csv") as csvfile:
# read csv
readCSV = csv.reader(csvfile, delimiter=',')
# print the number of items/rows in the csv file
print("Step 2: Confirm the total numbers:",int(len(readCSV))-1)
continue_text = input("Enter anything to continue")
# Reacquire (i.e. reset) readCSV iterator
readCSV = csv.reader(csvfile, delimiter=',')
# skip the headers
next(readCSV, None) # not used
i=0
for each_user in readCSV[1:]: # start at 1 to skip header
print(i+1," item:",str(each_user[0]))
i = i + 1
print("all done!")
选项 3(使用枚举为)
根据snakecharmerb的建议
with open("C:/Users/number-UK.csv") as csvfile:
# read csv (using list rather than iterator)
readCSV = list(csv.reader(csvfile, delimiter=','))
# print the number of items/rows in the csv file
print("Step 2: Confirm the total numbers:",int(len(readCSV))-1)
continue_text = input("Enter anything to continue")
# skip the headers
#next(readCSV, None) # not used (header skipped by using readCSV[1:])
for i, each_user in enumerate(readCSV[1:], start = 1):# start readCSV at 1
# to skip header
print(i," item:",str(each_user[0])) # i starts at 1,
# so no need to increment
print("all done!")
解决方法是将 csv 加载到 pandas 数据框中并测量其大小。
import pandas as pd
test = pd.read_csv('data.csv')
print(len(test))
您现在可以找到 for 循环之前的行数。
你可以这样做:
count = len(csvfile.readlines()))
f.seek(0)
count
将保存文件中的行数。 注意执行f.seek(0)
将文件读取指针移动到文件的开头,否则您将无法读取其他任何内容,因为readlines()
会一直读取到文件末尾。