[英]Issues with CSV file handling (Writing And Reading)
I decided to learn CSV file handling.我决定学习 CSV 文件处理。 In it, I can't understand what's happening at some point.在其中,我无法理解在某些时候发生了什么。 I have a question which is:我有一个问题是:
Write a program to create a file
voter.csv
file containing voter id, voter name, and voter age.编写一个程序来创建一个文件voter.csv
文件,其中包含选民 ID、选民姓名和选民年龄。 Read the file and display the number of records.读取文件并显示记录数。
So the wrong code I have right now is something like this:所以我现在的错误代码是这样的:
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)
m = 0
for i in a:
if a.line_num == 1:
continue
else:
m = m+1
print(m)
f.close()
Which always gives the number of records as 0
.它总是将记录数设为0
。
After all, I decided to work out what's wrong and I found out that the second for
loop after the first one is not working... Why is that happening?毕竟,我决定找出问题所在,我发现第一个循环之后的第二个for
循环不起作用......为什么会这样? How can this be fixed?如何解决这个问题?
This code will do what you want, in terms of printing out each row of the file as well as the total number of lines:此代码将按照您的要求执行,即打印出文件的每一行以及总行数:
import csv
n = int(input("Enter the number"))
with open('voter.csv','w',newline='') as f:
writer = csv.writer(f)
writer.writerow(['VID','VNAME','VAGE'])
for _ in range(n):
writer.writerow([
input("Enter the voter id"),
input("Name"),
input("Voter age")
])
m = 0
with open('voter.csv') as f:
for m, i in enumerate(csv.reader(f)):
print(i)
print("Total lines:", m)
If you want to actually re-read the file, the simplest thing is to re- open
it:如果您想真正重新读取文件,最简单的方法是重新open
它:
with open('voter.csv') as f:
for i in csv.reader(f):
print(i)
with open('voter.csv') as f:
m = sum(1 for _ in f)
print("Total lines:", m - 1)
Each open
call gets you a fresh iterator that starts at the beginning of the file.每个open
的调用都会为您提供一个从文件开头开始的新迭代器。 Each line you read from f
(or whatever you named the object you got from open()
) advances the iterator through the file.您从f
(或您从open()
获得的任何您命名的 object )读取的每一行都会使迭代器在文件中前进。 Starting a new for
loop over the file doesn't give you a new iterator, it just picks up where the current one left off.在文件上开始一个新for
循环不会给你一个新的迭代器,它只是从当前迭代器停止的地方开始。
The source of your confusion might be that a file iterator behaves differently from a list -- a list is not itself an iterator, it's an iterable that can create new iterators on command.您困惑的根源可能是文件迭代器的行为与列表不同——列表本身不是迭代器,它是一个可以根据命令创建新迭代器的迭代器。 Every time you start a new iteration over a list you're implicitly creating a new iterator, as if you'd re-opened a file.每次你在一个列表上开始一个新的迭代时,你都在隐式地创建一个新的迭代器,就好像你重新打开了一个文件一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.