You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSV文件读写问题:统计记录数始终为0的原因及解决方法

问题原因及修复方案

问题原因

csv.reader()返回的是一次性迭代器,当你用第一个for i in a:循环打印所有行时,已经把迭代器里的所有元素取完了。第二次再用for i in a:循环时,迭代器已经没有剩余元素可遍历,循环体根本不会执行,最终m的值保持初始的0。

修复方案

这里提供三种可行的修复方式:

方案1:将迭代器转为列表(支持多次遍历)

把csv.reader的结果转换成列表,列表可以被多次遍历:

import csv

# 写入逻辑保持不变
f = open('voter.csv','w',newline='')
obj = csv.writer(f)
field = ['VID','VNAME','VAGE']
obj.writerow(field)
n = int(input("Enter the number"))
for i in range(n):
    c = int(input("Enter the voter id"))
    nm = input("Name")
    a = int(input("Voter age"))
    x = [c,nm,a]
    obj.writerow(x)
f.close()

# 读取部分修改为列表形式
f = open('voter.csv')
# 将csv.reader结果转为列表
a = list(csv.reader(f))
# 打印所有行
for i in a:
    print(i)
m = 0
# 遍历列表统计数据行
for idx, i in enumerate(a):
    if idx == 0:  # 跳过表头行
        continue
    m += 1
print(m)
f.close()

方案2:重新打开文件进行统计

第一次遍历打印后,关闭文件再重新打开,让文件指针回到开头位置:

import csv

# 写入逻辑保持不变
f = open('voter.csv','w',newline='')
obj = csv.writer(f)
field = ['VID','VNAME','VAGE']
obj.writerow(field)
n = int(input("Enter the number"))
for i in range(n):
    c = int(input("Enter the voter id"))
    nm = input("Name")
    a = int(input("Voter age"))
    x = [c,nm,a]
    obj.writerow(x)
f.close()

# 第一次打开文件打印内容
f = open('voter.csv')
a = csv.reader(f)
for i in a:
    print(i)
f.close()

# 重新打开文件统计记录数
f = open('voter.csv')
a = csv.reader(f)
m = 0
for i in a:
    if a.line_num == 1:
        continue
    m += 1
print(m)
f.close()

方案3:一次遍历完成打印和统计(更高效)

不需要遍历两次,在第一次循环时同时完成打印和计数,减少IO操作:

import csv

# 写入逻辑保持不变
f = open('voter.csv','w',newline='')
obj = csv.writer(f)
field = ['VID','VNAME','VAGE']
obj.writerow(field)
n = int(input("Enter the number"))
for i in range(n):
    c = int(input("Enter the voter id"))
    nm = input("Name")
    a = int(input("Voter age"))
    x = [c,nm,a]
    obj.writerow(x)
f.close()

# 一次遍历完成打印与统计
f = open('voter.csv')
a = csv.reader(f)
m = 0
for idx, i in enumerate(a):
    print(i)
    if idx != 0:  # 跳过表头,统计数据行
        m += 1
print(m)
f.close()

内容的提问来源于stack exchange,提问作者user18825453

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:55:47