Opening a .txt file in Python
25,876
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)
Author by
Admin
Updated on December 11, 2020Comments
-
Admin over 3 years
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.
-
Niklas B. over 12 yearsThe file will not be closed if its completely empty. It would be more compact and clear to use
with open(inputFn, 'r') as f: return f.next()
-
John Machin over 12 years-1 (1) this reads only the first line, which is not what the OP said he wanted (2) if there is an
IOError
, it supresses the detailed error info (file doesn't exist? caller doesn't have permissions? etc?) and gratuitously callssys.exit
-
Alex Reynolds over 12 yearsThanks, I edited my answer to reflect the change for item 1. I only wanted to show the
try...except
block as a way to show how to think about error checking. Sorry this upset you.