Python csv.reader: How do I return to the top of the file?

When I’m moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like “file.seek(0)”. Is there anything like that for the csv module?

Thanks ahead of time 😉

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can seek the file directly. For example:

>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> for row in c: print row   # again
['1', '2', '3']
['4', '5', '6']

Method 2

You can still use file.seek(0). For instance, look at the following:

import csv
file_handle = open("somefile.csv", "r")
reader = csv.reader(file_handle)
# Do stuff with reader
file_handle.seek(0)
# Do more stuff with reader as it is back at the beginning now

This should work since csv.reader is working with the same.

Method 3

I’ve found the csv.reader and csv.DictReader a little difficult to work with because of the current line_num. making a list from the first read works well:

>>> import csv
>>> f = open('csv.txt')
>>> lines = list( csv.reader(f) ) # <-- list from csvReader
>>>
>>> for line in lines:
...  print(line)
['1', '2', '3']
['4', '5', '6']
>>>
>>> for line in lines:
...  print(line)
['1', '2', '3']
['4', '5', '6']
>>>
>>>lines[1]
['4', '5', '6']

this captures the optional first row used by the dictReader but lets you work with the list again and again and even inspect individual rows.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x