如何多次使用csv阅读器对象 [英] How to use csv reader object multiple times

查看:179
本文介绍了如何多次使用csv阅读器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个python项目.我打开了一个新的csv文件,其内容是

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

我正在做的是...

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)

问题是我只能打印一次值.csvvalidation()函数阅读器不起作用.如何多次使用阅读器对象.我无法打印其行值,我该怎么办?请给我一个解决方案.我不知道seek()(我认为它再次指向同一读者).所以我在第一个函数之后尝试了infile.seek(0),但没有用.什么都没发生

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

谢谢.

推荐答案

阅读器包裹在文件指针周围,当指针用完时,它就用完了.不要多次使用它,一次使用它,然后处理您读取的数据数组:

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)

是的,您的两个函数无需修改即可工作(除非它们已经损坏),因为列表,文件和csv阅读器都是可以迭代的可迭代".不是Python的宏...

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

这篇关于如何多次使用csv阅读器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆