Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from CSVs in Python repeatedly?

Tags:

python

csv

I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks.

orig = csv.reader(open("googlel.csv", "rb"), delimiter = ';')
goodrows = []
for feed in gotfeeds:    
   for link,comments in feed.items():
       for row in orig:
           print link
           if link in row[1]:
               row.append(comments)
               goodrows.append(row)
like image 400
matt Avatar asked May 19 '10 18:05

matt


People also ask

How do I read a CSV file twice in Python?

If you need to re-read the file, you can either close it and re-open it, or seek() to the beginning, i.e. add ordersFile. seek(0) between your loops. Show activity on this post. The reader object is like a generator, once you have iterate the values, you cannot begin a second loop to read the values again.

How many ways can you read a CSV file in Python?

There are two common ways to read a . csv file when using Python. The first by using the csv library, and the second by using the pandas library.

Can you read and write to a CSV file at the same time Python?

Python has a built-in module that allows the code to read, write and parse CSV data into Python code. In this post, we learned to read and write data in the form of a CSV file using Python.


2 Answers

You can "reset" the CSV iterator by resetting the read position of the file object.

data = open("googlel.csv", "rb")
orig = csv.reader(data, delimiter = ';')
goodrows = []
for feed in gotfeeds:    
   for link,comments in feed.items():
       data.seek(0)
       for row in orig:
           print link
           if link in row[1]:
               row.append(comments)
               goodrows.append(row)
like image 107
Cerin Avatar answered Oct 18 '22 13:10

Cerin


Making orig a list avoids the need to reset/reparse the csv:

orig = list(csv.reader(open("googlel.csv", "rb"), delimiter = ';'))
like image 35
unutbu Avatar answered Oct 18 '22 11:10

unutbu