How to use csv reader object multiple times

我们两清 提交于 2020-05-14 02:47:05

问题


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.


回答1:


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...




回答2:


It works. You should check your code again :)

with open("new.csv", "rb") as infile:
    reader = csv.reader(infile)
    first_row = next(reader, None)  
    checkduplicationcsv(reader)
    infile.seek(0)        # <- Add infile.seek(0)
    csvvalidation(reader)



回答3:


If you cannot read the whole file into memory you can create two readers by means of tee:

from itertools import tee
with open("new.csv", "rb") as infile:
    reader = csv.reader(infile)
    first_row = next(reader, None)  # skip the headers
    reader1, reader2 = tee(reader, 2)
    checkduplicationcsv(reader1)
    csvvalidation(reader2)


来源:https://stackoverflow.com/questions/42903157/how-to-use-csv-reader-object-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!