Skip to content
Advertisement

Issues with CSV file handling (Writing And Reading)

Sup geeks! As a very beginner to CSV files and modules, I am facing some issues while running my codes. At some point, it is acting a bit weird. My objective is to write a program to create a file voter.csv containing voter id, voter name, and voter age. And to read the file and display the number of records.

The code I’ve worked out is given below:

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 instead of giving the total number of records which was added. After all, I decided to work out what was 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?

This question was edited for its betterment. Thanks in advance.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement