Why can't I repeat the "for" loop for csv.Reader? (Python)

I am starting Python. Now I'm trying to find out why the second "for" loop does not work in the following script. I mean, I could only get the result of the first cycle β€œfor”, but none of the second. I copied and pasted the script and csv data into the following.

It will be useful if you tell me why this happens and how to make a second for for loop.

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
+11
source share
2 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’s nothing more to read. If you need to go through it again, you can find the beginning of the file:

fh.seek(0)

reset , .

, , :

data = list(read)

, , data.

+26

, csv , ,

def read_csv_data(path):
    """
        Reads CSV from given path and Return list of dict with Mapping
    """
    data = csv.reader(open(path))
    # Read the column names from the first line of the file
    fields = data.next()
    data_lines = []
    for row in data:
        items = dict(zip(fields, row))
        data_lines.append(items)
    return data_lines

+2

All Articles