【问题标题】:Create filename with metadata使用元数据创建文件名
【发布时间】:2018-11-23 01:39:38
【问题描述】:

是否可以创建具有某些属性的 md 文件并在 python 上将其保存为 .md 格式? 所以我有属性:

year="2018"
month="12"

我需要将其保存到具有必要属性的 2018_12_metadata.md 文件中。这是 md 文件的样子

{
  "year": "2018",
  "month": "12"
}

所以我有一些代码,但我可以找到如何将其保存为具有必要属性的 md 格式:

year="2018"
month="12"
path_folder="C:\\Users\" 
MD_output = path_folder + year +'-'+ month +'_metadata.md'
md_file - what should be here?
md_file.write(MD_output)

非常感谢您的帮助。

【问题讨论】:

    标签: python python-3.x markdown


    【解决方案1】:

    制作字典

    metadata = {
      "year": "2018",
      "month": "12"
    }
    

    设置你的文件路径

    path_folder="C:\\Users\\" 
    md_file = "{}\\{year}_{month}_metadata.md".format(path_folder, *metadata)
    

    打开一个文件并写入它

    with open(md_file, 'w') as f:
        f.write("foobar")
    

    或者,如果您只想将字典写入文件,请将其加载为 JSON

    import json
    with open(md_file, 'w') as f:
        json.dump(metadata, f)
    

    【讨论】:

      【解决方案2】:

      亲爱的,这是我找到的解决方案:

      result = {'year': '2018',
                'month': '12'}
      file_name="Check"
      with open(os.path.join(path_folder, '{}.md'.format(file_name)), mode='w') as md_file:
          json.dump(result, md_file, indent=2)
      

      感谢大家的帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-11
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        相关资源
        最近更新 更多