【问题标题】:Python filter records from csv looking-up another csvPython 从 csv 过滤记录查找另一个 csv
【发布时间】:2023-03-18 06:38:01
【问题描述】:

我正在尝试通过在 File-B 中从 File-A 中查找一些“ID”来创建一个 csv 文件,我们称之为 File-C。

If File-B has the 'ID' from File-A 
      THEN put the record in File-C.

查找文件具有以下 csv 格式:

File-A
ID,incr,event
1111.1234557,5,missing create

数据文件有'ID'属性和其他属性:

File-B
ID,incr,name,email,accountno
1111.1234557,5,john,emailaddress,22020233902

输出或 File-C 将与数据文件完全相同,但记录较少,因为它们是根据我们在查找文件中找到的内容进行过滤的。

我编写了以下代码,它给出了错误“索引超出范围”。我觉得这与循环通过的两个列表的大小有关。我不知道它们是如何连接的。

def read_from_file(csv_file):
    with open(csv_file, 'rt') as f:
        file_reader = csv.reader(f)
        next(file_reader, None)
        data = list(file_reader)
    return data


data_file= read_from_file('/CSV_RECORDS_20200308_A.csv')
lookup_file= read_from_file('/CSV_RECORDS_20200308_B.csv')

output_data = []

for row in lookup_file:
    for val in data_file:
        if row[0] == val[0]: ## FAILES HERE WITH ERROR 'IndexError: list index out of range'##
            output_data.append(row)


with open('/INSERTBACK_TEST.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(output_data)

完整的错误信息是:

Traceback(最近一次调用最后一次):

运行时_1 |文件“/opt/project/etl/landing/unibanks/code.py”,第 102 行,在

运行时_1 |如果行[0] == 值[0]:

运行时_1 | IndexError: 列表索引超出范围

我似乎无法弄清楚这一点。 任何帮助将不胜感激。

【问题讨论】:

  • CSV 看起来很奇怪,这是 Stack Overflow 上的格式问题吗? 请提供完整的错误消息以及minimal reproducible example
  • 是的,我只是添加了空格以提高可读性。我会删除它们。
  • 完整的错误信息是 Traceback(最近一次调用最后一次):runtime_1 |文件“/opt/project/etl/landing/unibanks/replica-dentist-recon.py”,第 102 行,在 runtime_1 |如果行[0] == val[0]:runtime_1 | IndexError: 列表索引超出范围
  • 这种信息应该放在你的帖子里,作为评论读起来很痛苦。
  • 用完整的错误信息更新了帖子。

标签: python csv filter compare


【解决方案1】:

错误告诉您从其中一个文件中读取了一些空列表。

val = []
print(val[0])
>>out
>>list index out of range

检查您的文件是否有空行。

【讨论】:

  • 非常感谢!我在查找文件的末尾有 1 个空行。
猜你喜欢
  • 2019-04-17
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多