[英]Compare 2 csv files and update columns
我有 2 个 csv 文件,其中有 2 行 3 列(id、name、value)我想比较。 如果其中一个文件添加了新行,则另一个文件也会更新。 同样,如果其中一列中的值发生更改,则更新另一个文件。
这是我尝试过的
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"]}')
我注意到迭代只发生一次。 我在这里做错了吗?
我注意到迭代只发生一次......?
在外循环有机会进行下一次迭代之前,内循环可能已经到达文件末尾。 尝试在内循环停止后将文件对象的指针移回开头。
with open(a, 'r') as f1, open(b, 'r') as f2:
...
for row_new in file2:
for row_old in file1:
if row_new['id'] == row_old['id']:
...
else:
print(f'create row {row_new["id"]}')
f1.seek(0)
有人会说嵌套的 for 循环是你做错的。 以下是一些需要考虑的问题/答案。
python update a column value of a csv file according to another csv file Python Pandas: how to update a csv file from another csv file
搜索python csv update one csv file based on another site:stackoverflow.com
基本上,您应该尝试只读取每个文件一次,并使用允许快速成员资格测试的数据类型,如集合或字典。
您的 DictReaders 将为您的每一行提供一个{'id':x,'name':y,'value':z}
字典 - 导致您使用嵌套的 for 循环来比较一个文件中的所有行与其他。 您可以使用键的id
列创建单个字典,字典值可以是列表 - {id:[name,value],id:[name,value],...}
这可能会使处理更容易。
您还打开了两个文件以供阅读, open(...,'r')
,因此在修复其他内容后,您可能会发现文件未更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.