C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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'
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())
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