Python open file exception handling


To open a file, Python has a open()built-in function called , through which the user can read or write to the file, but if in any case the file is missing or inaccessible to the compiler, then, we encounter a FileNotFoundError. This article describes how to handle Python's file exceptions.


Python open() file function

This function opens the file, loads all contents, and returns it as a file object.

General syntax:

open(filename, mode='r')

This function has two parameters. One is the filename or the entire file path; the other is the access mode, which determines what must be done with the file.

There are various modes, including r (read-only), w (write-only), a (append-only), rb (Read-only in Binary format), etc.


Python open file exception

Suppose we try to open a file that does not exist or enter the wrong file path by mistake, resulting in a FileNotFound exception.

Sample code:

file1 = open("myfile.txt",'r')
# Reading from file
print(file1.read())
file1.close()

output:

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 gives an error that there is no such file or directory because the compiler found that the file to open is missing.


Use try-except to handle exceptions when Python reads files

One of the best ways to solve this missing file problem is that the code is vague and contains some errors. We wrap that part of code in a try block.

The try block is executed first. An exception is thrown when the file cannot be found.

The remaining code in the try block is skipped and control jumps to the except block. In the except block, we mentioned the type of error thrown.

Exceptions are handled in an except block. If there are no exceptions 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")

output:

FileNotFoundError successfully handled

The statements in the except block are printed in the output due to an error in the try block. So by using this trick we can handle exceptions in our code by displaying any message in the output despite getting an error message.

Guess you like

Origin blog.csdn.net/fengqianlang/article/details/131505716