【问题标题】:output json file for each yaml file input为每个 yaml 文件输入输出 json 文件
【发布时间】: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。如果你想为循环的每次迭代使用不同的文件名,你将需要在某个地方使用一个变量。

标签: python json yaml


【解决方案1】:

这应该适合你:

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.replace('.yaml', '.json') # change the file extension
        with open(json_file, 'w') as outfile:
            json.dump(yaml.safe_load(f), outfile)

【讨论】:

  • 有一个后续问题,如果想将输出文件保存到/tmp目录并在我进行一些转换后删除json文件,该怎么做?
  • 这是一个完全独立的问题,如果您提出另一个问题并在此处链接,我可以回答
  • stackoverflow.com/questions/61742480/… 刚刚发布了这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多