When I try to run
import csv
import sys
import operator
fieldnames = ["A","B","C","D","E"]
surveyfile = open("source.csv", "r")
left_file = open("left.csv",'wb')
right_file = open("right.csv",'wb')
left_reader = csv.DictReader(surveyfile, fieldnames=fieldnames, delimiter=",")
left_writer = csv.DictWriter(left_file, fieldnames, delimiter=",")
sortedlefts = sorted(left_reader,key=lambda x:float(x["B"]))
right_reader = csv.DictReader(surveyfile, fieldnames=fieldnames, delimiter=",")
right_writer = csv.DictWriter(right_file, fieldnames, delimiter=",")
sortedrights = sorted(right_reader,key=lambda x:float(x["B"]), reverse=True)
for row in sortedlefts:
if row["E"] == "l":
left_writer.writerow(row)
for row in sortedrights:
if row["E"] == "r":
right_writer.writerow(row)
Nothing happens in the “right.csv” file. But if I take everything that has to do with making the right.csv file out and put it into a different program, it works fine. Do I need to end that for loop? Is it some problem with using the same reader for both?
The input file is likely exhausted, so yes it has to do with re-using the
readerinstance.Not sure why you expect the
readerobject to magically know when it’s supposed to re-deliver the data.You need to be more explicit about this, I would simply recommend re-creating the reader as needed.