在Python中打开.txt文件

6 投票
2 回答
26636 浏览
提问于 2025-04-17 09:11

我正在尝试用下面这个函数在Python中打开一个.txt文件。

def get_my_string():
   """Returns a string of the text"""
   f = open("/home/Documents/text.txt", 'r')
   string = str(f.read())
   f.close()
   return string

我希望“string”能够包含打开的文件里的文本内容。但是在调用上面的函数后,“string”却变成了一个空列表。

2 个回答

0

其实你不需要在文件路径中写上 home/documents 这些部分,只要你的 Python 文件和文本文件保存在同一个文件夹里就可以了。你只需要用 Open() 函数打开文本文件,文件名用字符串表示,比如 Open("text.txt")。括号可能不是必须的,但加上它们也可以正常工作。

10
def get_my_string():
    """Returns the file inputFn"""

    inputFn = "/home/Documents/text.txt"

    try:
        with open(inputFn) as inputFileHandle:
            return inputFileHandle.read()

    except IOError:
        sys.stderr.write( "[myScript] - Error: Could not open %s\n" % (inputFn) )
        sys.exit(-1)

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答