繁体   English   中英

在Python中打开.txt文件

[英]Opening a .txt file in 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”是一个空列表。

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()函数打开文本文件,然后在字符串中打开文本文件名即Open( “text.txt”)您可能不需要括号,但它可能适用于它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM