Python Forum

Full Version: Print only works once
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm using the following code to read a tiny csv file into a Dictionary and then print part of it twice. The first print works but the second print seems to do nothing despite it being identical code. No error message is generated. What am I missing?

import csv

UserDB = {}

FileName = 'UserDB.csv'
UserDB = csv.DictReader(open(FileName, 'r'), delimiter=',', quotechar='"')

for line in UserDB:
    print (line['User'])

for line in UserDB:
    print (line['User'])
The csv file just contains..

User,Password
James,1234
Will,5678
Fred,1111
Harry,3333
After the first loop the DictReader is exhausted, i.e. you are at the end of the file.
That makes sense. How do I reset the "Line" pointer to the start again?

(Sep-20-2017, 03:51 PM)buran Wrote: [ -> ]After the first loop the DictReader is exhausted, i.e. you are at the end of the file.

Can I check my understanding...

I thought that this line was scanning the dictionary UserDB not the file UserDB.csv?
for line in UserDB:
Perhaps I misunderstand how DictReader works. Does it read the file into a dictionary you create (eg UserDB) or does it just provide a means to access the file (UserDB.csv) as if it was a dictionary?
from the docs:
Quote:Return a reader object which will iterate over lines in the given csvfile.
i.e. the reader object is not dictionary. Think of it like iterable of dicts. you iterate over the lines (of the reader) one at a time, then it scans the line, which is dict and returns 'user'
import csv

file_name = 'UserDB.csv'
with open(file_name, 'r') as dbf:
    db_reader = csv.DictReader(dbf, delimiter=',', quotechar='"')
    for line in db_reader:
        print (line['User'])
    dbf.seek(0) #reset to begining of file
    for line in db_reader:
        print (line['User'])
Thanks for that. Looks like I need to do some more reading.
If the data is short enough, just read the entire file into a buffer,
then you don't have to read it twice.
import csv
 
file_name = 'UserDB.csv'
csv_data = None
with open(file_name, 'r') as dbf:
    db_reader = csv.DictReader(dbf, delimiter=',', quotechar='"')
    csv_data = dbf.read()

for line in csv_data:
    print (line['User'])

for line in csv_data:
    print (line['User'])
Written on the fly, not tested
Thanks for the replies, we're learning slowly :-)