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

2024-09-28 17:02:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

REQUEST DETAILS
RITM :: RITM1234
STASK :: TASK1234
EMAIL :: abc@abc.com
USER :: JOHN JOY

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

像这样的,大概有100行

我们有没有办法将其存储为模板,或者将其存储在“.toml”或类似文件中,并在python中写入值(右::)


Tags: com模板taskemailrequestcontentdetailsjohn
2条回答

对于模板创建,我使用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 }}

您可能需要对其进行一点修改,但主要的事情是存在的

使用$将所有输入作为占位符,并将其另存为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=name)
'Hey, Bob!'

相关问题 更多 >