【发布时间】:2017-12-05 19:48:39
【问题描述】:
我是 Python 新手。 按照这个例子: https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f
我有一个使用模板字符串 “${PERSON_NAME}” 的消息模板文件 message.txt 。该字符串将替换为该人的实际姓名。
所以我正在使用这个函数,但有些事情不正确,因为它给了我奇怪的输出”
from string import Template
def read_template(filename):
with open(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt', 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read(100)
return Template(template_file_content)
print(read_template(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt'))
我错过了什么?
【问题讨论】:
-
你为什么使用
string.Template类?为什么你认为输出是“奇怪的”?鉴于您编写了一个显式返回Template对象的函数,您期望什么? -
如果你只是想读取文件,你不需要使用
string.Template,直接返回template_file.read(100)即可。当然,除非您这样做,在这种情况下,这是预期的行为。您通过printing 调用实例的__str__方法。 -
阅读模板文件只是我项目的一部分。我只是想确保该功能正常运行,以便继续。
-
@ekhumoro,所以输出
<string.Template object at 0x000000789AA19080>是否正确?抱歉,就像我说的,我对 python 了解不多……还没有。 -
@Oleg。当然如此。请回答我之前评论中的所有问题。
标签: python python-3.x templates