Search code examples
pythonpython-3.xjinja2

jinja2 how save output file with virables name


i have arg.yml file with

filename : 'custom_file_name'
data1 : 5028
data2 : 1111
...

and script.py which saves an output file named output.txt

from jinja2 import Environment, FileSystemLoader
import yaml

env = Environment(loader=FileSystemLoader("."))
templ = env.get_template("template.txt")

with open('arg.yml') as f:
    arg = yaml.safe_load(f)

with open("output.txt", 'w') as f:
    f.write(templ.render(arg))

how to rename output.txt to file with variable name filename from arg.yaml

to custom_file_name.txt


Solution

  • you could just :

    ...
    with open(f"{arg["filename"]}.txt", 'w') as f:
        f.write(templ.render(arg))