【问题标题】:parse a csv into python dictionaries by structured range通过结构化范围将 csv 解析为 python 字典
【发布时间】:2018-12-04 05:11:42
【问题描述】:

我有一个 csv 文件,其中包含转储到行中并以逗号分隔的信息范围。每行是一个单独的行,并且记录集由表示 startrecord(具有唯一 id)和 stoprecord(匹配 id)的行“预定”。记录书签之间的数据多种多样,没有一定的重复性。

StartRecord, ID
name, value, other
name, value,value,value
EndRecord, ID
StartRecord, ID
name, value, other
something, another, another, something new, different
EndRecord, ID
StartRecord, ID
various, name, value, name, value, other
EndRecord, ID

我正在使用 csv 阅读器读取记录并迭代行。如何将 startrecord 和 endrecord 之间的数据捕获到单独的字典对象中(在本例中,我有 3 条记录)?

【问题讨论】:

  • CSV 文件是如何创建的?如果可以创建文件,那么每个 ID 都有一行您可以在阅读时拆分为新行
  • @Travis - csv 是从导出程序创建的,具有固定格式。这是一个较旧的应用程序,不可扩展。

标签: python csv parsing


【解决方案1】:

continue 语句在这里应该会有所帮助。试试这个。

import csv

dict = {}
current_id = ''

with open('filename.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        print(row)
        if row[0] == 'StartRecord':
            current_id = row[1]
            dict[row[1]] = []
            continue
        if row[0] == 'EndRecord':
            continue
        dict[current_id].append(row)

print(dict)

编辑:我意识到如果您的 csv 文件在逗号后有空格,如示例中的那样,您可能需要修改 delimiter 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2022-07-04
    • 2017-10-26
    • 2021-05-01
    • 2023-03-16
    • 2018-05-16
    相关资源
    最近更新 更多