【问题标题】:Read curly braces yaml to python将花括号 yaml 读取到 python
【发布时间】:2021-04-27 23:36:56
【问题描述】:

我正在testing.yaml中设置一些参数

a :
    one : 
        file_name : 10/a_one 10.xlsx
        index_col : 0

我可以通过下面的脚本在python中毫无问题地阅读

with open('testing.yaml') as f:
    data = ruamel.yaml.load(f, Loader=ruamel.yaml.Loader)
print(f"{data['a']['one']['file_name']}")

输出是10/a_one 10.xlsx。我将使用pd.read_excel() 从此输入中保存dataframe。但是,如果我想包含从 python 中更改的可格式化字符串,则会出现错误。例如:假设我希望能够在 python 中更改10,我编辑testing.yaml

a :
    one : 
        file_name : {month}/a_one {month}.xlsx
        index_col : 0

然后python中的脚本会说

month = 10
with open('testing.yaml') as f:
    data = ruamel.yaml.load(f, Loader=ruamel.yaml.Loader)
print(f"{data['a']['one']['file_name']}")

我希望在这里再次输出10/a_one 10.xlsx,我能以某种方式实现吗?我不想直接在 YAML 文件中进行所有更改的原因是,一些格式信息(在本例中为 month = 10)来自另一个在 python 中读取的 excel 文件。

【问题讨论】:

    标签: python dictionary yaml


    【解决方案1】:

    请注意,f-strings 确实是一种执行任意代码的方式。正如这个问题的答案How do I convert a string into an f-string?

    因此建议不要尝试使用 f-strings 来格式化外部数据。相反,请尝试使用旧的 string.format 方法:

    print(data['a']['one']['file_name'].format(month=month))
    

    在您的 yaml 中,您需要将花括号放入字符串中:

    a :
        one : 
            file_name : "{month}/a_one {month}.xlsx"
            index_col : 0
    

    否则你会得到这样的解析器错误:

    yaml.parser.ParserError: while parsing a block mapping
      in "testing.yaml", line 3, column 9
    expected <block end>, but found '<scalar>'
      in "testing.yaml", line 3, column 28
    

    使用上面的python语句固定的yaml文件产生所需的输出:

    10/a_one 10.xlsx
    

    【讨论】:

    • 哇哦,我以为f"{var}"(var).format(var) 完全一样。感谢您的信息和解决方案!
    猜你喜欢
    • 2019-07-05
    • 2023-03-31
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2012-01-18
    • 2021-07-04
    • 1970-01-01
    • 2023-01-29
    相关资源
    最近更新 更多