I have two csv files and i am using one csv to search all records from another csv and update its status. I have two tables and looking for IP and PROTOCOL from search table in input.csv. If it is there, then the EXISTS column is updated to 'No'. I am stuck where both the protocol and ip are same for two or more records, but they have different port. It is updating only one record.
import csv
IP, EXISTS, PROTOCOL = 'IP', 'Exists', 'Protocol' # Field names referenced.
# Read entire input file into a list.
with open('input.csv', 'r', newline='') as inp:
reader = csv.DictReader(inp)
inputs = list(reader)
# Update input rows that match data in search.csv file.
with open('search.csv', 'r', newline='') as sea:
sea_reader = csv.DictReader(sea)
for row in sea_reader:
protocol, ip = row[PROTOCOL], row[IP]
for input_ in inputs:
if input_[PROTOCOL] == protocol and input_[IP] == ip: # Match?
input_[EXISTS] = 'No'
break
# Write updated input.csv data out into a file.
with open('input_updated.csv', 'w', newline='') as outp:
fieldnames = inputs[0]
writer = csv.DictWriter(outp, fieldnames)
writer.writeheader()
for input_ in inputs:
writer.writerow(input_)
print('done')
Input.csv
Name | IP | Protocol | Port | Exists |
---|---|---|---|---|
l1 | 192.132.16.02 | HTTP | 80 | |
l2 | 192.132.16.03 | SSL | 8443 | |
l3 | 192.132.16.03 | SSL | 443 | |
l4 | 192.132.16.04 | SSL | 443 |
search.csv
No | Protocol | IP | Port |
---|---|---|---|
1 | HTTP | 192.132.16.02 | 80 |
2 | SSL | 192.132.16.03 | 443 |
3 | SSL | 192.132.16.03 | 8443 |
Here in search.csv there are two records which has same protocol and ip but different port. In the result it is just including one record and not both. I tried adding port in the condition too but it does not work