Home > Software engineering >  Issues with CSV file handling (Writing And Reading)
Issues with CSV file handling (Writing And Reading)

Time:08-02

I decided to learn CSV file handling. 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. 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.

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? How can this be fixed?

CodePudding user response:

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:

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. Each line you read from f (or whatever you named the object you got from open()) advances the iterator through the file. 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.

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.

  • Related