如何写一个文件与固定模板在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中写入值(::的右侧)?

使用$将所有输入作为占位符,并保存为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!'

创建模板时使用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 }}

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

最新更新