[Solved]: IOError in Python


In Python, IOError is subclass of EnvironmentError. IOError is occurred when an input/output operation like open() file, or a method or a simple print statement is failed due to IO reason like “Disk full” or “File not found”

Example of Python IOError

In the below code, the xyz.txt file is not exist because of that the program will throw IOError exception. This IOError handle in the program through try-except block.

import sys
def readFile():
    try:
        f = open ( "xyz.txt", 'r' )
    except IOError as e:
        print (e)
readFile()

Output

[Errno 2] No such file or directory: 'xyz.txt'

This IOError exception message will print only when exception occurred.

Conclusion

In Python, IOError is a result of incorrect file name or file path. IOError occurred in multiple cases and these conditions can be handled using try except code block. Implementation way to handle IOError by try-except can check by above example.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s