Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return to the beginning of a DictReader?

Tags:

python

If I call the company_at_node method (shown below) twice, it will only print a row for the first call. I thought maybe that I needed to seek back to the beginning of the reader for the next call, so I added self.companies.seek(0) to the end of the company_at_node method but DictReader has no attribute seek. Since the file is never closed (and since I didn't get an error message to that effect), I didn't think this was a ValueError i/o operation on closed file (which there are numerous questions about on SO)

Is there a way to return to the beginning of a DictReader to iterate through a second time (i.e. a second function call)?

class CSVReader:
    def __init__(self):
        f = open('myfile.csv')
        self.companies = csv.DictReader(f)


    def company_at_node(self, node):
        for row in self.companies:
            if row['nodeid'] == node:
                print row
        self.companies.seek(0)
like image 812
Leahcim Avatar asked Dec 19 '22 17:12

Leahcim


1 Answers

You need to do f.seek(0) instead of DictReader. Then, you can modify your code to be able to access file. This should work:

class CSVReader:
    def __init__(self):
        self.f = open('myfile.csv')
        self.companies = csv.DictReader(f)


    def company_at_node(self, node):
        for row in self.companies:
            if row['nodeid'] == node:
                print row
        self.f.seek(0)
like image 65
PseudoAj Avatar answered Dec 21 '22 10:12

PseudoAj