【问题标题】:How to read content of text file using function如何使用函数读取文本文件的内容
【发布时间】: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


【解决方案1】:

您可以使用readlines()函数读取文件。

def read_from_file():
    with open('file.txt', 'r') as file:
         content = file.readlines()
     print content

这将打印文件的全部内容。

另外readline() 函数将从文件中读取一行,而readlines() 将读取文件的全部内容

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2016-10-14
    相关资源
    最近更新 更多