【问题标题】:Compare 2 csv files and update columns比较 2 个 csv 文件并更新列
【发布时间】: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"]}')

我注意到迭代只发生一次。我在这里做错了吗?

【问题讨论】:

标签: python python-3.x csv


【解决方案1】:

我注意到迭代只发生一次...?

在外循环有机会进行下一次迭代之前,内循环可能已经到达文件末尾。尝试在内循环停止后将文件对象的指针移回开头。

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 循环是你做错了。以下是一些需要考虑的 SO 问题/答案。

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} dict - 导致您使用嵌套的 for 循环来比较一个文件中的所有行与另一个文件中的每一行。您可以使用 id 列作为键创建单个字典,而字典值可以是列表 - {id:[name,value],id:[name,value],...},这可能会使处理更容易。


您还打开了两个文件以供阅读,open(...,'r'),因此您可能会在修复其他内容后发现您的文件没有改变。

【讨论】:

  • 我遇到了一个错误AttributeError: 'DictReader' object has no attribute 'seek'
  • @twingo f1 是文件对象,而不是 DictReader。
  • 对不起,我的错。错误是ValueError: I/O operation on closed file.
  • 已修复。这是一个缩进问题。非常感谢!
  • @twingo - 考虑也接受答案。 What should I do when someone answers my question?
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多