Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this python code conflict with itself?

Tags:

python

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?

like image 472
user1879422 Avatar asked Jul 16 '26 19:07

user1879422


1 Answers

The input file is likely exhausted, so yes it has to do with re-using the reader instance.

Not sure why you expect the reader object 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.

like image 120
unwind Avatar answered Jul 18 '26 08:07

unwind