Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use csv reader object multiple times

Tags:

python

csv

reader

I am doing a python project.I opened a new csv files and its contents are

 A     |  B
  -------------
  1.  200 | 201   
  2.  200 | 202
  3.  200 | 201
  4.  200 | 203
  5.  201 | 201
  6.  201 | 202
  ...........

And what I am doing is...

def csvvalidation(readers):
    for row in readers:
        print row
def checkduplicationcsv(reader):
    datalist = []
    for row in reader:
        print row
        content = list(row[i] for i in range(0,3))
        datalist.append(content)     
with open("new.csv", "rb") as infile:
    reader = csv.reader(infile)
    first_row = next(reader, None)  # skip the headers
    checkduplicationcsv(reader)
    csvvalidation(reader)

The problem is I can print the values only one time.The csvvalidation() function reader is not working.How can I use the reader object multiple times.I can't print its row values.What can I do?Please give me a solution.And I am not aware of seek() (I think that its pointing to the same reader again).So I tried infile.seek(0) after the first function but no use.nothing happens

Thanks in advance.

like image 318
bob marti Avatar asked Feb 01 '26 10:02

bob marti


1 Answers

The reader is wrapped around a file pointer, and when that is used up, it's used up. Don't use it multiple times, use it once and then work with the array of data you read:

with open("new.csv", "rb") as infile:
    reader = csv.reader(infile)
    first_row = next(reader, None)  # skip the headers
    data = list(reader)             # read everything else into a list of rows

checkduplicationcsv(data)
csvvalidation(data)

Yes, your two functions will work without modification (unless they were already broken), because a list, a file, and a csv reader are all "iterables" that can be iterated over. Ain't Python grand...

like image 61
alexis Avatar answered Feb 03 '26 00:02

alexis