1
使用string.Template
我想將值替換到模板中的值存儲在單獨的文件中,我可以循環使用。將模板替換值存儲在單獨的文件中
循環是簡單的部分。然後我想運行我的模板上的
result = s.safe_substitute(title=titleVar, content=contentVar)
。我只是有點難以用什麼格式將這些值存儲在文本文件中,以及如何使用python讀取該文件。
使用string.Template
我想將值替換到模板中的值存儲在單獨的文件中,我可以循環使用。將模板替換值存儲在單獨的文件中
循環是簡單的部分。然後我想運行我的模板上的
result = s.safe_substitute(title=titleVar, content=contentVar)
。我只是有點難以用什麼格式將這些值存儲在文本文件中,以及如何使用python讀取該文件。
你在找什麼叫電話serialization。在這種情況下,你想序列化的字典,如
values = dict(title='titleVar', content='contentVar')
有5方式進行序列化,使用XML,鹹菜,YAML,JSON格式的例子。以下是你如何使用JSON做到這一點:
import string
import json
values = dict(title='titleVar', content='contentVar')
with open('/tmp/values', 'w') as f:
json.dump(values, f)
with open('/tmp/values', 'r') as f:
newvals = json.load(f)
s = string.Template('''\
$title
$content''')
result = s.safe_substitute(newvals)
print(result)