将dictreader转换成字典的优雅方式

2024-10-04 07:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我这样做:

headers = ['name', 'accum', 'hi', 'active', 'first', 'last', 'max', 'dirty']
filename = "C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec"

with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile:

    for line in csvfile:
        if all(header in line for header in headers):
            reader = csv.DictReader(csvfile, fieldnames=headers)
            break

效果很好。在

但我不想为了使用我的数据而打开文件。有没有一种优雅的方式,只把我的数据放在RAM中,而不需要打开文件?在

理想情况下,我希望能够关闭文件,然后能够访问我的数据做这样的事情

^{pr2}$

Tags: 文件数据csvfilenameinforlineusers
1条回答
网友
1楼 · 发布于 2024-10-04 07:28:51

尽管你遗漏了一些重要的细节,我还是继续做了一些假设,结果是:

table = {}

with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile:
    for line in csvfile:
        if all(header in line for header in headers):
            for row in csv.DictReader(csvfile, fieldnames=headers):
                name_row = table.get(row['name'], {})
                name_row[row['name']] = row['address']

相关问题 更多 >