I have the code to open the file, but how do I display what is in the file in my shell.
outputFile = open('test.txt', 'r')
data = outputFile.read
outputFile.close
I have the code to open the file, but how do I display what is in the file in my shell.
outputFile = open('test.txt', 'r')
data = outputFile.read
outputFile.close
()
to call the read
and close
methods. outputFile.read
is a function; outputFile.read()
is the result of actually calling that function (i.e. reading data from the file).print
the data
that you get from calling read()
if you want to see it in the console.outputFile = open('test.txt', 'r')
data = outputFile.read()
outputFile.close()
print(data)
Hello world!
If you use outputFile
as a context manager (via the with
keyword), you don't need to call close()
; the context is automatically closed at the end of the indented block.
with open('test.txt', 'r') as outputFile:
print(outputFile.read())
Hello world!
Well this should work:
with open('test.txt') as f:
contents = f.read()
print(contents)