-2

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
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 2
    See [this example](https://realpython.com/read-write-files-python/#reading-and-writing-opened-files) of opening and printing `dog_breeds.txt`. – jarmod Dec 08 '21 at 16:49

2 Answers2

2
  • You need to use () 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!
Samwise
  • 68,105
  • 3
  • 30
  • 44
1

Well this should work:

with open('test.txt') as f:
    contents = f.read()
    print(contents)
Bennnii
  • 111
  • 6