繁体   English   中英

比较 python 中的 2 个 csv 文件时列出超出范围的索引

[英]list index out of range when comparing 2 csv files in python

我想比较和更新 2 个 csv 文件。 如果 file1 比 file2 多出一行,则应该更新 file2。

这是我的代码:

with open(file1, 'r') as f1, open(file2, 'r') as f2:
    old_file = list(csv.DictReader(f1))
    new_file = list(csv.DictReader(f2))
            
    print(len(old_file)) # It is 20
    print(len(new_file)) # It is 23

    for row in range(len(new_file)):
        if len(old_file) < row :
            if new_file[row]['id'] in old_file[row]:
                print(row)   

此代码在第二个if statement中引发错误。 如果我删除它并打印行信息,它工作得很好。 这里有什么问题?

你的情况是错误的方法。

for row in range(len(new_file)):
    if len(old_file) < row :
        if new_file[row]['id'] in old_file[row]:
            print(row)   

应该

for row in range(len(new_file)):
    if row < len(old_file):
        if new_file[row]['id'] in old_file[row]:
            print(row)   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM