在Python中打开.txt文件

2024-05-13 12:59:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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”是一个空列表。


Tags: 文件ofthe函数texttxthomeget
2条回答
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)

只要python文件和文本文件保存在同一个文件夹中,就不需要home/documents部分,只需要使用open()函数和字符串中的文本文件名来打开文本文件,这样就可以打开(“text.txt”),您可能不需要方括号,但可以使用它们。

相关问题 更多 >