Skip to main content
 首页 » 编程设计

python之如何多次使用 csv 阅读器对象

2025年05月04日14freeliver54

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

 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() 函数阅读器不工作。我如何多次使用阅读器对象。我无法打印其行值.What can I do?Please give me a solution.And I not aware of seek() (I think that its pointing to the same reader again).所以我尝试了infile.seek (0) 在第一个函数之后但没有用。没有任何反应

提前致谢。

请您参考如下方法:

读取器围绕着一个文件指针,当它用完时,它就用完了。不要多次使用它,使用一次,然后使用您读取的数据数组:

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 不是很棒吗...