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

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']

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.

Tags:

Python

Csv