Python IOError Fix, os.path.existsReview IOError. Use os.path.exists and the try-raise construct.
IOError. File handling is fraught with errors. A file may not exist, or it may not be accessible. In Python we encounter an IOError in these situations. We can prevent, or simply handle, IOErrors.
Except keyword. Sometimes we cannot prevent all possible errors. Python in these cases provides the except keyword to deal with failure cases.
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())
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. We can prevent the IOError by first testing the path.exists. This returns true if the file exists, and false otherwise. Here, the method returns false—so open() 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.
And The Python program does not terminate. The error is trapped and handled with grace.
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")
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-2021 sam allen.
see site info on the changelog.