Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I repeat the 'for' loop for csv.Reader?

Tags:

python

csv

I am a beginner of Python. I am trying now figuring out why the second 'for' loop doesn't work in the following script. I mean that I could only get the result of the first 'for' loop, but nothing from the second one. I copied and pasted my script and the data csv in the below.

It will be helpful if you tell me why it goes in this way and how to make the second 'for' loop work as well.

My SCRIPT:

import csv

file = "data.csv"

fh = open(file, 'rb')
read = csv.DictReader(fh)

for e in read:
    print(e['a'])

for e in read:
    print(e['b'])

"data.csv":

a,b,c
tree,bough,trunk
animal,leg,trunk
fish,fin,body
like image 876
miyazaki_tara Avatar asked Jun 22 '12 04:06

miyazaki_tara


People also ask

How do I loop a csv file in Python?

Step 1: Load the CSV file using the open method in a file object. Step 2: Create a reader object with the help of DictReader method using fileobject. This reader object is also known as an iterator can be used to fetch row-wise data. Step 3: Use for loop on reader object to get each row.

What is quotechar?

quotechar - It refers to the single character string that will be used to quote values if special characters (like delimiter) appears inside the field. It defaults to " . quoting - controls when quotes should be generated by the writer or recognized by the reader. It can take one of the following constants: csv.

What is a CSV file in Python?

Source code: Lib/csv.py. The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180.


1 Answers

The csv reader is an iterator over the file. Once you go through it once, you read to the end of the file, so there is no more to read. If you need to go through it again, you can seek to the beginning of the file:

fh.seek(0)

This will reset the file to the beginning so you can read it again. Depending on the code, it may also be necessary to skip the field name header:

next(fh)

This is necessary for your code, since the DictReader consumed that line the first time around to determine the field names, and it's not going to do that again. It may not be necessary for other uses of csv.

If the file isn't too big and you need to do several things with the data, you could also just read the whole thing into a list:

data = list(read)

Then you can do what you want with data.

like image 139
BrenBarn Avatar answered Sep 21 '22 10:09

BrenBarn