python - 如何在打印项目之前计算 CSV 中的行数?
问题描述
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(使用枚举作为)
正如蛇怪所建议的那样
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!")
推荐阅读
- javascript - Javascript/html 未定义的输入
- python-3.x - 如何检索特殊条目。和..在一个文件夹中
- javascript - 下面这段代码的未定义输出有问题
- rust - 在结构中使用 trait 对象而不需要类型参数
- python - OOP继承,如何在python中获取父类型的变量?
- excel - 跟踪命名范围内注释中的单元格更改
- gitversion - gitversion 主线没有正确地基于主线的版本?
- python - 为什么我在尝试录制音频时出现错误?“Sounddevice.PortAudioError”
- python - 在python中用三个内核(x,y,z)卷积一个3D数组
- generics - 返回 impl trait + 'static 的泛型函数的生命周期要求