gpt4 book ai didi

python - 使用 DictReader 时替换字段名

转载 作者:行者123 更新时间:2023-12-04 13:32:59 26 4
gpt4 key购买 nike

我有一个 test.csv文件:

foo,bar,foobar,barfoo

1,2,3,4
5,6,7,8
9,10,11,12

以及以下 CSV解析器:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import json

f = open ( 'test.csv', 'r' )

reader = csv.DictReader( f, fieldnames = ( "foo","bar","foobar","barfoo" ))

out = json.dumps( [ row for row in reader ], ensure_ascii=False, encoding="utf-8")

print out

有没有一种简单的方法来替换输出中的字段名,而无需更改 CSV 的标题?文件?

我目前的输出是这样的:
[
{
"foobar":"foobar",
"foo":"foo",
"bar":"bar",
"barfoo":"barfoo"
},
{
"foobar":"3",
"foo":"1",
"bar":"2",
"barfoo":"4"
},
{
"foobar":"7",
"foo":"5",
"bar":"6",
"barfoo":"8"
},
{
"foobar":"11",
"foo":"9",
"bar":"10",
"barfoo":"12"
}
]

我能得到这样的东西吗:
[
{
"id":"foobar",
"email":"foo",
"name":"bar",
"phone":"barfoo"
},
{
"id":"3",
"email":"1",
"name":"2",
"phone":"4"
},
{
"id":"7",
"email":"5",
"name":"6",
"phone":"8"
},
{
"id":"11",
"email":"9",
"name":"10",
"phone":"12"
}
]

最佳答案

最简单的方法是设置:

reader.fieldnames = "email", "name", "id",  "phone"

如果需要,您也可以保存旧的字段名。

关于python - 使用 DictReader 时替换字段名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17039539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com