首页 > 解决方案 > 如何在打印项目之前计算 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 文件的行数,有人知道如何实现吗?非常感谢。

标签: pythonpython-3.xcsvread.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!")

推荐阅读