如何在python中使用固定模板写入文件?

zzlelutf  于 11个月前  发布在  Python
关注(0)|答案(2)|浏览(113)

我有一个固定的模板要写这是相当长的,

REQUEST DETAILS
RITM :: RITM1234
STASK :: TASK1234
EMAIL :: [email protected]
USER :: JOHN JOY

CONTENT DETAILS
TASK STATE :: OPEN
RAISED ON :: 12-JAN-2021
CHANGES :: REMOVE LOG

像这样的东西,也就是100行
我们有没有办法将它存储为模板或存储在“.toml”或类似的文件中,并在python中写入值(::的右侧)?

xcitsw88

xcitsw881#

使用$将所有输入作为占位符,并将其保存为txt文件。然后使用模板

from string import Template
t = Template(open('template.txt', 'r'))
t.substitute(params_dict)

样品

>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name='Bob')
'Hey, Bob!'
yqlxgs2m

yqlxgs2m2#

对于模板创建,我使用jinja:

from jinja2 import FileSystemLoader, Template

# Function creating from template files.
def write_file_from_template(template_path, output_name, template_variables, output_directory):
    template_read = open(template_path).read()
    template = Template(template_read)
    rendered = template.render(template_variables)
    output_path = os.path.join(output_directory, output_name)
    output_file = open(output_path, 'w+')
    output_file.write(rendered)
    output_file.close()
    print('Created file at  %s' % output_path)
    return output_path


journal_output = write_file_from_template(
        template_path=template_path,
        output_name=output_name,
        template_variables={'file_output':file_output, 
            'step_size':step_size, 
            'time_steps':time_steps},
        output_directory=output_directory)

使用名为file.extension.TEMPLATE的文件:

# This is a new file :
{{ file_output }}
# The step size is :
{{ step_size }}
# The time steps are :
{{ time_steps }}

你可能需要稍微修改一下,但主要的东西都在那里。

相关问题