Print only works once - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Print only works once (/thread-5145.html) |
Print only works once - CWatters - Sep-20-2017 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 RE: Print only works once - buran - Sep-20-2017 After the first loop the DictReader is exhausted, i.e. you are at the end of the file. RE: Print only works once - CWatters - Sep-20-2017 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? RE: Print only works once - buran - Sep-20-2017 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']) RE: Print only works once - CWatters - Sep-20-2017 Thanks for that. Looks like I need to do some more reading. RE: Print only works once - Larz60+ - Sep-20-2017 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 RE: Print only works once - CWatters - Sep-23-2017 Thanks for the replies, we're learning slowly :-) |