File IO with Exception Handling
try:
with open('/File/Location/File_name.txt', mode='r') as my_file:
print(my_file.read())
except:
print("File does not exist: FileNotFoundError")
print('This line was run...')
You can also have specific cases:
try:
with open('/File/Location/File_name.txt', mode='r') as my_file:
print(my_file.read())
except TypeError:
print("There was a type error")
except FileNotFoundError:
print("File does not exist: FileNotFoundError")
except:
print("Different types of error from the predicted ones")
print('This line was run...')
The
except
clause will run only if there is aTypeError
(Which is an object)
There is also an additional clause called finally
finally
try:
with open('/File/Location/File_name.txt', mode='r') as my_file:
print(my_file.read())
except:
print("There was an error")
finally:
print('THIS WILL ALWAYS RUN')
finally
is a clause that will always run, no matter what
If you are dealing with files there are sometimes errors that variables are not accessible
In that case you would implement this in another
try
blockThis can get confusing though so be careful
try:
my_file = open(file_name, mode='r')
try:
print(my_file.read())
except IOError:
print("There was an error")
finally:
my_file.close()
print('The file was closed')
except:
print('There was another error')
IOError
is a type where it handles all the file issues, such as:No permission
Was not accessible
Does not have write permissions
Does not exist
Any issue with working with the file
Last updated