【发布时间】:2020-12-06 13:39:24
【问题描述】:
我有 2 个包含 2 行 3 列(id、名称、值)的 csv 文件,我想比较它们。如果其中一个文件添加了新行,则另一个文件也会更新。同样,如果其中一列中的值发生更改,则会更新另一个文件。
这是我尝试过的
a = '/path/to/file'
b = 'path/to/file'
with open(a, 'r') as f1, open(b, 'r') as f2:
file1 = csv.DictReader(f1)
file2 = csv.DictReader(f2)
for row_new in file2:
for row_old in file1:
if row_new['id'] == row_old['id']:
for k1, v1 in row_new.items():
for k, v in row_old.items():
if row_old[k1] == row_new[k]:
if v1 != v:
print(f'updated value for col {k}')
v1 = v
else:
print('Nothing to update')
else:
print(f'create row {row_new["id"]}')
我注意到迭代只发生一次。我在这里做错了吗?
【问题讨论】:
-
当您检查/打印程序中各个点的值和/或条件时,是否存在明显的异常行为?如果您正在使用 IDE现在是学习其调试功能或内置 Python debugger 的好时机。在程序中的关键点打印 stuff 可以帮助您跟踪正在发生或未发生的事情。 What is a debugger and how can it help me diagnose problems?
标签: python python-3.x csv