Back to: Python Programming
0
Python can read the contents of a file. Place a TXT file (called “pythonTest.txt” in C;\data on your computer, or in a location you’ll remember, and put two or three lines of text in it.
with open("c:\\data\\pythonTest.txt") as file:
print (file.read())
Outputs the entire contents of my file:
Hello Students,
This file was saved on my HDD at C:\data
Python can read the contents of this file.
The file will be closed automatically after being read. We can confirm this:
with open("c:\\data\\pythonTest.txt") as file:
print (file.read())
print(file.closed) # <-- Prints “True” if the file is closed.
If the file doesn’t exist in this location, an exception will interrupt the program so we should add an exception handler to stop errors from breaking the code.
try:
with open("c:\\data\\pythonTest.tx") as file:
print(file.read())
except FileNotFoundError:
print("That file was not found :(")
The code now has a typo in the path (missing a t at the end). Instead of breaking, the code will handle the exception and notify the user that the code cannot be found.