【发布时间】:2020-05-07 00:14:00
【问题描述】:
在 python 中想要为每个 yaml 文件输入输出 json。 到目前为止,无法写入与 yaml 文件名相同的 json 文件作为输入。
import yaml
import json
import datetime
import os, glob
path = './test/json'
for filename in glob.glob(os.path.join(path, '*.yaml')):
with open(filename, 'r') as f:
json_file = 'filename.json'
with open(json_file, 'w') as outfile:
json.dump(yaml.safe_load(f), outfile)
这会输出到一个 json 文件而不是单独的文件。
【问题讨论】:
-
您将 JSON 文件命名为文字字符串
filename.json。如果你想为循环的每次迭代使用不同的文件名,你将需要在某个地方使用一个变量。