问题描述:

I am attempting to write the entire row of a .csv file that has been found modified via a For, In loop. I have managed to get the program to write the keys to a csv file but I can't get it to write the associated values along with those keys. I'm unsure if I need another loop nested in or if I am just making a mistake with the syntax.

import csv

def make_billing_dict(csv_dict_reader):

bdict = {}

for entry in csv_dict_reader:

key = entry['BillingNumber']

bdict[key] = entry

return bdict

with open('old/MTBT.txt') as csv_file:

old = csv.DictReader(csv_file)

old_bills = make_billing_dict(old)

with open('new/MTBT.txt') as csv_file:

new = csv.DictReader(csv_file)

new_bills = make_billing_dict(new)

diff = file("diff/diff.csv", "wb" )

writer = csv.writer(diff)

for keys in old_bills:

if old_bills[keys]['CustomerName'] != new_bills[keys]['CustomerName'] or old_bills[keys]['IsActive'] != new_bills[keys]['IsActive'] or old_bills[keys]['IsPayScan'] != new_bills[keys]['IsPayScan']:

writer.writerow([keys])

#Used to send records to the console

# print (new_bills[keys]['BillingNumber'],new_bills[keys]['CustomerName'],new_bills[keys]['IsActive'],new_bills[keys]['IsPayScan'],new_bills[keys]['IsCreditHold'],new_bills[keys]['City'],new_bills[keys]['State'])

#print set(new_bills.keys()) - set(old_bills.keys())

Also, I have noticed that if I add a new key and entry into the new file it causes no problems but if I remove a record it causes a key error. I understand why, because it's looking for a key that's in the original dict but is there any way around this issue?

相关阅读:
Top