简体   繁体   English

没有遍历csv文件python3的所有行

[英]Not Iterating through all lines from a csv file python3

I am quite new to python3 and I am sure my question is very basic. 我是python3的新手,我敢肯定我的问题是非常基本的。 I have been looking online for some help and the closest I got came from thread Find Common Region in two CSV File in PYTHON 我一直在网上寻求帮助,而我最接近的是来自PYTHON中两个CSV文件中的“查找公用区域”线程

However in my case it seems it is not iterating through everyline and stop at the first one. 但是就我而言,似乎并没有遍历每一行并在第一行停止。 SO in my first csv I have 2 lines, lets say: 因此,在我的第一个csv中,我有2行,可以这样说:

A,1,A1 A,1,A 1

B,2,B2 B,2,B2

now in my second csv I have a thousand lines, something like 现在在我的第二个CSV中,我有一千行,类似

A,1,B5 A,1,B5

A,2,A2 A,2,A2

B,2,C6 B,2,C6

B,3,C7 B,3,C7

C,3,D7 C,3,D7

C,4,D8 C,如图4所示,D8

...... ......

my code is as follow: 我的代码如下:

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])

However, my output is There is a match A 1 It only finds the first match and not the other matche: B 2 I am not sure what is wrong in my iterations: 但是,我的输出是有一个匹配项A 1它只找到第一个匹配项,而不找到另一个匹配项:B 2我不确定在迭代中出了什么问题:

Thank you in advance for your help 预先感谢您的帮助

After the first pass of your loops, file csv2 will be at end of file. 在循环的第一遍之后,文件csv2将位于文件末尾。 Subsequent reads will return an empty string. 随后的读取将返回一个空字符串。 This is true even if you create a new CSV reader using the same file object. 即使使用相同的文件对象创建新的CSV阅读器,也是如此。 For this reason the second match is not found because the second file is effectively not processed. 因此,找不到第二个匹配项,因为实际上未处理第二个文件。

The easiest solution is to call csv2.seek(0) after processing the second file, i,e: 最简单的解决方案是在处理第二个文件(即csv2.seek(0)后调用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)

Put the contents in a list : 将内容放在列表中:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM