Catch IOError Exception in Python



In Python, an IOError (or OSError in latest versions) occurs when an input/output operation fails. For example, when we are trying to read a file that doesn't exist, writing to a file that is read-only, or accessing a corrupted device.

You can catch IOError using a try-except block to handle file input/output errors in Python. For compatibility with Python 3, we need to use OSError or catch both using a tuple.

Using try-except Block

You can catch IOError using a try-except block. This helps you handle file-related errors without crashing the program.

Example

In this example, we try to open a file that does not exist, and the IOError is caught and handled -

try:
   file = open("nofile.txt", "r")
except IOError:
   print("IOError: Could not open file.")

We get the following output -

IOError: Could not open file.

Using IOError with Exception Object

You can capture the exception object to access more details about the error using the as keyword.

Example

In the following example, we capture the error message using as keyword and print it -

try:
   f = open("nofile.txt", "r")
except IOError as e:
   print("Caught IOError:", str(e))

The output shows the detailed error message -

Caught IOError: [Errno 2] No such file or directory: 'nofile.txt'

IOError When Writing to Read-Only File

Writing to a read-only file or protected location can also raise an IOError

This error happens when the program doesn't have permission to write to the given location. It can also occur if the file system is locked or the disk is full.

Example

In this example, we try to write to a restricted file path, which raises an IOError -

try:
   with open("/readonly.txt", "w") as f:
      f.write("test")
except IOError as e:
   print("Write error:", str(e))

This will raise an IOError if the file cannot be written to -

Write error: [Errno 30] Read-only file system: '/readonly.txt'

IOError in Modern Python Versions

In Python 3, IOError was merged into the OSError, so you can rely on OSError alone to catch both kinds of errors, though for backward compatibility, you can still use except OSError or except (IOError, OSError).

Example

In this example, we handle both IOError and OSError together to catch a wider range of possible file-related errors -

try:
   with open("nofile.txt", "r") as f:
      data = f.read()
except (IOError, OSError) as e:
   print("File read error:", str(e))

We get the following output -

File read error: [Errno 2] No such file or directory: 'nofile.txt'
Updated on: 2025-05-22T16:57:13+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements