我正在尝试将许多 JSON 文件写入 CSV 文件。每个 JSON 文件都有几个键,但不同的文件有不同的键。这里以三个JSON文件为例。
文件A:
{"a": 1, "c": 2}
文件B:
{"b": 5, "d": 3}
文件 C:
{"a": 6, "b": 7}
我想要一个像这样的四列三行的 CSV 文件(为简单起见省略了逗号):
a b c d
1 2
5 3
6 7
一种方法是使用 csv writer 通过多个 try/except 语句。但这变得不可行,因为我正在处理大量 key 。有没有其他选择?
请您参考如下方法:
假设您提前知道所有可能的字段名称csv.DictWriter已经为此提供了解决方案,使用构造函数的 restval 参数:
If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional
restvalparameter.
因此指定 csv.DictWriter(..., restval="") 将用单个空格替换任何缺失值,尽管默认情况下 restval 设置为 ""(一个空字符串)这可能对您更有用。
基本上你的代码应该是这样的:
import csv, json
all_fields = ["a","b","c","d"]
all_files = ["A.json","B.json","C.json"]
with open("OUTPUT.csv", "w") as output_file:
writer = csv.DictWriter(output_file,all_fields)
writer.writeheader()
for filename in all_files:
with open(filename,"r") as in_file:
writer.writerow(json.load(in_file))
