【问题标题】:Not Iterating through all lines from a csv file python3不遍历 csv 文件 python3 中的所有行
【发布时间】:2014-12-18 23:33:15
【问题描述】:

我对 python3 很陌生,我确信我的问题非常基本。 我一直在网上寻求帮助,我得到的最接近的来自线程 Find Common Region in two CSV File in PYTHON

但是,就我而言,它似乎并没有遍历每一行并停在第一行。 所以在我的第一个 csv 中,我有 2 行,可以说:

A,1,A1

B,2,B2

现在在我的第二个 csv 中,我有一千行,类似于

A,1,B5

A,2,A2

B,2,C6

B,3,C7

C,3,D7

C,4,D8

......

我的代码如下:

read1 = csv.reader(csv1) 
for row1 in read1:
    read2 = csv.reader(csv2)
    for row2 in read2:
        if row1[0] == row2[0] and row1[1] == row2[1]:
           print('There is a match', row1[0], row1[1])

但是,我的输出是 有一个匹配 A 1 它只找到第一个匹配项而不找到另一个匹配项:B 2 我不确定我的迭代出了什么问题:

提前感谢您的帮助

【问题讨论】:

    标签: python csv python-3.x iteration


    【解决方案1】:

    第一次循环后,文件csv2 将位于文件末尾。后续读取将返回一个空字符串。即使您使用相同的文件对象创建新的 CSV 阅读器也是如此。由于这个原因,没有找到第二个匹配项,因为实际上没有处理第二个文件。

    最简单的解决方案是在处理完第二个文件后调用csv2.seek(0),即:

    read1 = csv.reader(csv1) 
    for row1 in read1:
        read2 = csv.reader(csv2)
        for row2 in read2:
            if row1[0] == row2[0] and row1[1] == row2[1]:
               print('There is a match', row1[0], row1[1])
        csv2.seek(0)
    

    【讨论】:

    • 谢谢,我尝试添加 csv2.seek(0) 但我收到错误消息,AttributeError: '_csv.reader' object has no attribute 'seek' 然后另一个答案来了并且起作用了。感谢您的宝贵时间。
    • 没问题,我的回答解释了您遇到问题的原因,而另一个答案可能是更好的解决方案。请注意,csv2 是一个文件对象。看起来您可能尝试过 read2.seek(0) 而不是 csv2.seek(0)
    • 是的,也许我做了 =S,对此感到抱歉!这很尴尬。无论如何都干杯。
    【解决方案2】:

    将内容放入列表中:

    import  csv
    with open(file1) as f1,open(file2) as f2:
        rd1, rd2 = csv.reader(f1) ,list(csv.reader(f2))
        for row1 in rd1:
            for row2 in rd2:
                if row1[0] == row2[0] and row1[1] == row2[1]:
                    print('There is a match', row1[0], row1[1])
    

    【讨论】:

    • 不用担心,不客气。如果文件非常大,您可以使用 seek 但是对于一千个元素,您会很好
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    相关资源
    最近更新 更多