Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Searching .csv file with rows from a different .csv file

Tags:

python

csv

All -

I am attempting to read a single row from a csv file and then have it search another csv file.

I have a masterlist.csv that has a single column called empID. It contains thousands of rows of 9 digit numbers. As well I have ids.csv that also contains a single column called number. It contains hundreds of rows. I am attempting to pull a row from the ids.csv do a search on the masterlist.csv and print out whether it has been found. Then it needs to move to the next row in ids.csv until each row in ids.csv has been searched within the masterlist.csv. I thought it would be as simple as this, however it is not throwing any errors nor returning any results.

Using 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")

Edit: Adding snippet of data used for testing.

enter image description here

enter image description here

like image 774
Zachary Hanshaw Avatar asked Nov 24 '25 17:11

Zachary Hanshaw


1 Answers

Content of master.csv

EmpId
111111111
222222222
333333333
444444444

Content of ids.csv:

Number
111111111
999999999
444444444
555555555
222222222

Code:

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

Output:

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>

More shorter version of code without CSV module

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"
like image 138
Dinesh Pundkar Avatar answered Nov 27 '25 07:11

Dinesh Pundkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!