我正在尝试编写通过For,In循环找到修改的.csv文件的整行。我已经设法让程序将密钥写入csv文件,但我无法将其与这些密钥一起写入关联值。我不确定我是否需要嵌套其他循环,或者我是否只是在语法上犯了错误。
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())
另外,我注意到如果我在新文件中添加一个新密钥和条目,它会导致没有问题,但如果我删除一条记录,则会导致密钥错误。我理解为什么,因为它正在寻找原始字典中的密钥,但有没有办法解决这个问题?