Python - 使用来自不同.csv文件的行搜索.csv文件

时间:2016-09-13 18:50:18

标签: python csv

全部 -

我正在尝试从csv文件中读取一行,然后让它搜索另一个csv文件。

我有一个masterlist.csv,它有一个名为empID的列。它包含数千行9位数字。我也有ids.csv,它还包含一个名为number的列。它包含数百行。我试图从ids.csv中取一行在masterlist.csv上搜索并打印出它是否已找到。然后它需要移动到ids.csv中的下一行,直到在masterlist.csv中搜索到ids.csv中的每一行。 我认为它会像这样简单,但它不会抛出任何错误,也不会返回任何结果。

使用Python 2.7.12     import csv

masterReader = csv.reader(open("masterlist.csv", "rt"), delimiter=",")
idsReader = csv.reader(open("ids.csv", "rt"), delimiter=",")


for number in idsReader:
    for empID in masterReader:
        if number == empID:
            print (" Found in MasterFile")
        else:
            print ("Is Not Found in MasterFile")

编辑:添加用于测试的数据片段。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

master.csv的内容

EmpId
111111111
222222222
333333333
444444444

ids.csv的内容:

Number
111111111
999999999
444444444
555555555
222222222

<强>代码:

import csv

f1 = file('master.csv', 'r')
f2 = file('ids.csv', 'r')

c1 = csv.reader(f1)
c2 = csv.reader(f2)

idlist = list(c2)
masterlist = list(c1)

for id in idlist[1:]:
    found = False
    #Need to ignore heading thats why masterlist[1:]
    for master in masterlist[1:]:
        if id == master:
            found = True
    if found:
        print "Found in master file"
    else:
        print "Not found in master file"

f1.close()
f2.close()

<强>输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Found in master file
Not found in master file
Found in master file
Not found in master file
Found in master file

C:\Users\dinesh_pundkar\Desktop>

没有CSV模块的更短版本的代码

with open('master.csv','r') as master:
    with open('ids.csv','r') as id:
        id_list = id.readlines()[1:]
        master_list = master.readlines()[1:]
        for id in id_list:
            if id in master_list:
                print "Found in master file"
            else:
                print "Not found in master file"

答案 1 :(得分:0)

通过使用交集的csv.DictReader作为读者对象,可以轻松找到两者共有的数字(不确定文件是否实际包含单个列) :

with open("masterlist.csv") as f1, open("ids.csv") as f2:
    masterReader = csv.DictReader(f1)
    idsReader = csv.DictReader(f2)

    common = set(row['empID'] for row in masterReader) \
           & set(row['number'] for row in idsReader)
    print(common)

或者使用列表成员资格检查来查找idsReader中包含的masterReader中的行:

masterReader = [row['empID'] for row in masterReader]

for row in idsReader:
    if row['number'] in masterReader:
        print (" Found in MasterFile")
    else:
        print ("Is Not Found in MasterFile")

P.S。考虑到您的问题的更新,您可能甚至不需要csv模块来执行此操作