Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

dictionary - Read curly braces yaml to python

i'm setting some parameters in testing.yaml

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

which i can read in python through the script below with no problem

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

the output is 10/a_one 10.xlsx. i will save a dataframe from this input using pd.read_excel(). however, if i want to include formattable strings which are changed from within python, i get an error. for example: say i want to be able to change the 10 in python, i edit testing.yaml

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

and the script in python would then say

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

i expect the output to be 10/a_one 10.xlsx again here, can i achieve this somehow? the reason i don't want to make all changes within in the YAML-file directly, is because that some formatting information (in this case month = 10) is coming from another excel-file which is read within python.

question from:https://stackoverflow.com/questions/65863178/read-curly-braces-yaml-to-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please note that f-strings are indeed a way of executing arbitrary code. As can be read in the answer to this question How do I convert a string into an f-string?

So it is advisable not to try to use f-strings for formatting external data. Instead, try to stick to the good old string.format method:

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

In your yaml you need to put the curly-braces into a string:

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

Otherwise you will get a Parser error like this:

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

With the fixed yaml file above python statement produces the desired output:

10/a_one 10.xlsx

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...