- Python Open File Exception
try-exceptto Handle Exceptions When Reading a File in Python
To open a file, Python has a built-in function called
open() by which the user can read or write to a file, but if, in any circumstance, the file is missing or unable to access by the compiler, so, we are encountered by a
FileNotFoundError. This article will look at how to handle Python’s file exceptions.
open() File Function
This function opens the file, loads all the content, and return it as a file object.
This function takes two arguments. One is the file name or the whole file path; the other is access mode, which decides what action must be performed on a file.
There are various modes, including
rb (Read-only in Binary format), etc.
Python Open File Exception
Suppose we are trying to open a file that does not exist or mistakenly entered the wrong file path, resulting in a
file1 = open("myfile.txt",'r') # Reading from file print(file1.read()) file1.close()
FileNotFoundError Traceback (most recent call last) C:\Users\LAIQSH~1\AppData\Local\Temp/ipykernel_4504/3544944463.py in <module> ----> 1 file1 = open("myfile.txt",'r') 2 3 # Reading from file 4 print(file1.read()) 5 FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
We see that the
open function is giving an error that says
No such file or directory because the file to be open is found missing by the compiler.
try-except to Handle Exceptions When Reading a File in Python
One of the finest cures to this missing file problem is that the code is ambiguous and contains some errors. We wrap that part of our code in the
try block executes first. When the file is not found, the exception is raised.
The remaining code in the
try block is skipped, and the control jumps into the
except block. In the
except block, we mention the error type raised.
Exceptions are handled in the
except block. If there is no exception in the
try block, the
except clause will not execute.
Consider the following example.
try: file1 = open("myfile.txt",'r') # Reading from file print(file1.read()) file1.close() except FileNotFoundError: print("FileNotFoundError successfully handled")
FileNotFoundError successfully handled
Since there was an error in the
try block, the statement in the
except block was printed in the output. So by using this trick, we can handle exceptions in our code by displaying any message in the output despite getting an error message.