Reputation: 557
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.
Upvotes: 1
Views: 1750
Reputation: 2526
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
Upvotes: 3