Reputation:
I'm trying to open a .txt file in Python with the following function.
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
I want "string" to be a string of the text from the opened file. However, after calling the function above, "string" is an empty list.
Upvotes: 6
Views: 26722
Reputation: 1
You don't really need the home/documents part as long as the python file and text file are saved in the same folder, you only need to open the textfile using the Open() function and the textfile name in a string so Open("text.txt") you may not need the brackets but it may work with them.
Upvotes: 0
Reputation: 96976
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)
Upvotes: 10