我正在尝试使用以下函数在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”是一个空列表。
答案 0 :(得分: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)
答案 1 :(得分:0)
只要python文件和文本文件保存在同一文件夹中,您就不需要home / documents部分,只需要使用Open()函数和字符串中的文本文件名打开文本文件所以打开(“text.txt”)你可能不需要括号,但它可能适用于它们。