您可以使用标准库字符串模板:
所以你有一个文件src与
$title
...
$subtitle
...
$list
和一本字典
d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }
那很简单
from string import Template
#open the file
filein = open( 'foo.txt' )
#read it
src = Template( filein.read() )
#do the substitution
src.substitute(d)
然后可以打印src
当然,正如Jammon所说,您还有许多其他好的模板引擎(这取决于您要执行的操作。标准字符串模板可能是最简单的)
完整的工作示例
foo.txt
$title
...
$subtitle
...
$list
example.py
from string import Template
#open the file
filein = open( 'foo.txt' )
#read it
src = Template( filein.read() )
#document data
title = "This is the title"
subtitle = "And this is the subtitle"
list = ['first', 'second', 'third']
d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }
#do the substitution
result = src.substitute(d)
print result
然后运行example.py
$ python example.py
This is the title
...
And this is the subtitle
...
first
second
third