Here's the script:
import csv
with open('file1.csv', newline='') as f1, open('file2.csv', newline='') as f2:
reader1 = list(csv.reader(f1))
reader2 = list(csv.reader(f2))
for row1 in reader1:
for row2 in reader2:
if row2[0] == row1[0]:
row2.pop(0)
for item in row2:
row1.append(item)
with open('merged.csv', 'w', newline='') as fout:
writer1 = csv.writer(fout)
for row in reader1:
print(row)
writer1.writerow(row)
file1.csv:
ssid,loc,date,time
00:13,loc1,"Jan 1, 2013",1330
01:14,loc2,"Feb 2, 2013",1440
01:15,loc3,"Mar 3, 2013",1550
01:16,loc4,"Apr 4, 2013",1660
02:AA,loc5,"May 5, 2013",1700
02:BB,loc6,"Jun 6, 2013",1800
01:CC,loc7,"Jul 7, 2013",1900
file2.csv:
ssid,user,IP,mac
00:13,user1,192.168.1.2,AA:B1
01:14,user2,192.168.1.3,BB:C2
01:15,user3,192.168.1.4,CC:D3
01:16,user4,192.168.1.5,DD:E4
01:CC,user5,192.168.1.6,EE:F5
01:dd,user6,192.168.1.7,FF:G6
The script works, but it has occurred to me that the for loop that compares row2[0] with row1[0] and appends the items in row2 to row1 might be more efficient as a list comprehension. However being a python neophyte I'm not quite up to it yet. Any suggestions (in the form of code, or algorithms/pseudo code as a teaching aid) would be appreciated.
P.S. this isn't homework, I'm teaching myself python and using this script at work

New Topic/Question
Reply



MultiQuote







|