我确实有字典,每个值都是一个列表。
我想将单个项目写入单独的 JSON 文件。例如
data_to_write = {"Names":["name1", "name2", "name3"], "email":["mail1", "mail2", "mail3"]}
现在我想要 3 个 json data1.jsob, data2.json, data3.json,即以下(近似)格式。
data1.jsob, data2.json, data3.json
数据1.json
{ Name: name1, email: mail1 }
数据2.json
{ Name: name2, email: mail2 }
等等。
我目前的做法是
for file_no in range(no_of_files): for count, (key, info_list) in enumerate(data_to_write.items()): for info in info_list: with open( os.path.join(self.path_to_output_dir, str(file_no)) + ".json", "a", ) as resume: json.dump({key: info}, resume)
但这是错误的。任何帮助表示赞赏。
您可以使用 pandas 为您完成工作。将字典读入数据帧,然后迭代数据帧的行以生成每一行的 json:
import pandas as pd data_to_write = {"Names":["name1", "name2", "name3"], "email":["mail1", "mail2", "mail3"]} df = pd.DataFrame(data_to_write).rename(columns={'Names':'Name'}) for i in range(len(df)): jstr = df.iloc[i].to_json() with open(f"data{i+1}.json", "w") as f: f.write(jstr)
输出(每一行都在一个单独的文件中):
{"Name":"name1","email":"mail1"} {"Name":"name2","email":"mail2"} {"Name":"name3","email":"mail3"}