Loop through csv.DictReader lines more than once

I open the file and read it with csv.DictReader

. I repeat it twice, but the second time nothing is printed. Why is this and how can I get it to work?

with open('MySpreadsheet.csv', 'rU') as wb:
    reader = csv.DictReader(wb, dialect=csv.excel)
    for row in reader:
        print row

    for row in reader:
        print 'XXXXX'

# XXXXX is not printed

      

+3


source to share


4 answers


You read the entire file the first time you run it, so there’s nothing to read the second time. Since you are not using the csv data the second time, it would be easier to count the number of rows and just loop over that range a second time.

import csv
from itertools import count

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)
    row_count = count(1)

    for row in reader:
        next(count)
        print(row)

for i in range(row_count):
    print('Stack Overflow')

      

If you need to iterate over the raw csv data again, try opening the file again. Most likely, you should be repeating some of the data that you saved the first time, instead of reading the file again.



with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print('Stack Overflow')

      

If you don't want to open the file again, you can search for the beginning, skip the title, and repeat again.

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

    f.seek(0)
    next(reader)

    for row in reader:
        print('Stack Overflow')

      

+7


source


add wb.seek(0)

(goes back to the beginning of the file) and next(reader)

(skips the header line) before your second loop.



+1


source


You can try to keep the dict list and output

input_csv = []
with open('YourCsv.csv', 'r', encoding='UTF-8') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        input_csv.append(row)

for row in input_csv:
    print(row)

for row in input_csv:
    print(row)

      

+1


source


You can create a list of dictionaries, each dictionary representing a string in your file, and then count the length of the list, or use list indexing to print each dictionary.

Something like:

with open('YourCsv.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    rowslist = list(reader)

for i in range(len(rowslist))
    print(rowslist[i])

      

+1


source







All Articles