Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

csv

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 ;)

like image 618
Nope Avatar asked Jan 10 '09 21:01

Nope


People also ask

How do I read the first row of a CSV file in Python?

Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. Step 2: Create a reader object by passing the above-created file object to the reader function. Step 3: Use for loop on reader object to get each row.

How do I read an entire CSV file in Python?

csv file in reading mode using open() function. Then, the csv. reader() is used to read the file, which returns an iterable reader object. The reader object is then iterated using a for loop to print the contents of each row.


2 Answers

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'] 
like image 111
Federico A. Ramponi Avatar answered Sep 21 '22 22:09

Federico A. Ramponi


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.

like image 43
Evan Fosmark Avatar answered Sep 21 '22 22:09

Evan Fosmark