HomeSearch

Python IOError Fix, os.path.exists

This Python article shows an IOError and how to prevent the error. It uses os.path.exists and the try-raise construct.
IOError. File handling is fraught with errors. A file may not exist. It may not be accessible. In Python we encounter an IOError in these situations. We can prevent, or simply handle, IOErrors.
Example. This program causes an IOError to occur. The file "nope.txt" is most likely not present on the computer. The open() method raises an IOError with the "No such file or directory" message.
Python program that causes IOError # An invalid path. name = "/nope.txt" # Attempt to open the file. with open(name) as f: print(f.readline()) Output Traceback (most recent call last): File "...", line 7, in <module> with open(name) as f: IOError: [Errno 2] No such file or directory: '/nope.txt'
Exists. Next, we can prevent the IOError from happening by first testing the path.exists() method. This returns true if the file exists, and false otherwise. Here, the method returns false—so the open() method is never reached.

And: No error is ever encountered, because we avoid trying to open the file in the first place.

Python program that uses os.path.exists import os # A file that does not exist. name = "/nope.txt" # See if the path exists. if os.path.exists(name): # Open the file. with open(name) as f: print(f.readline())
Except example. This example uses a try-raise construct to capture errors. When the open() method raises an error, control flow enters the except-block. The Python program does not terminate. The error is trapped and handled with grace.Error
Python program that handles IOError try: # Does not exist. name = "/nope.txt" # Attempt to open it. with open(name) as f: print(f.readline()) except IOError: # Handle the error. print("An error occurred") Output An error occurred
Summary. Part of handling files is handling errors. The two tasks cannot be easily separated. In Python the IOError is an important file-handling error. And we can handle or fix it in many ways.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls