gpt4 book ai didi

python - 在 python 中编辑 CSV 文件,它从 python 中的另一个 json 文件读取值

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:02 25 4
gpt4 key购买 nike

我想编辑一个 csv 文件,它从 python 2.7 中的另一个 json 文件中读取值我的 csv 是:a.csv

a,b,c,d
,10,12,14
,11,14,15

我的json文件是a.json

{"a":20}

我希望我的“a”列将尝试在 json 文件中进行匹配。如果他们匹配。它应该从 json 复制该值并将其粘贴到我的 csv 文件,我的 csv 文件的最终输出应该如下所示。

a,b,c,d
20,10,12,14
20,11,14,15

到目前为止,我尝试过的是

 fileCSV = open('a.csv', 'a')

fileJSON = open('a.json', 'r')
jsonData = fileJSON.json()

for k in range(jsonData):
for i in csvRow:
for j in jsonData.keys():
if i == j:
if self.count == 0:

self.data = jsonData[j]
self.count = 1
else:

self.data = self.data + "," + jsonData[j]

self.count = 0
fileCSV.write(self.data)
fileCSV.write("\n")
k += 1
fileCSV.close()
print("File created successfully")

如果有人能帮助我,我将非常感激。请忽略任何语法和缩进错误。谢谢。

最佳答案

一些基本的字符串解析会让你到达这里。我写了一个脚本,它适用于你提到的简单场景。

检查这是否解决了您的问题:

import json
from collections import OrderedDict


def list_to_csv(listdat):
csv = ""
for val in listdat:
csv = csv+","+str(val)
return csv[1:]

lines = []
csvfile = "csvfile.csv"
outcsvfile = "outcsvfile.csv"
jsonfile = "jsonfile.json"

with open(csvfile, encoding='UTF-8') as a_file:
for line in a_file:
lines.append(line.strip())

columns = lines[0].split(",")
data = lines[1:]

whole_data = []
for row in data:
fields = row.split(",")
i = 0
rowData = OrderedDict()
for column in columns:
rowData[columns[i]] = fields[i]
i += 1
whole_data.append(rowData)

with open(jsonfile) as json_file:
jsondata = json.load(json_file)

keys = list(jsondata.keys())

for key in keys:
value = jsondata[key]
for each_row in whole_data:
each_row[key] = value

with open(outcsvfile, mode='w', encoding='UTF-8') as b_file:
b_file.write(list_to_csv(columns)+'\n')
for row_data in whole_data:
row_list = []
for ecolumn in columns:
row_list.append(row_data.get(ecolumn))
b_file.write(list_to_csv(row_list)+'\n')

CSV 输出不写入源文件,而是写入另一个文件。输出文件也总是被截断和写入,因此是 'w' 模式。

关于python - 在 python 中编辑 CSV 文件,它从 python 中的另一个 json 文件读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34390128/

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