< previous | Table of Contents | järgmine > |
7.6 ERROR HANDLING IN FILE OPERATIONS
COMMON FILE ERRORS
The most common file error is the FileNotFoundError
, which occurs when trying to open a file that does not exist.
Here's an example in Thonny of trying to open a file that does not exist.
However, important to note that if we'd specified a mode, such as r
, even though the file didn't previously exist, it would be created.
Though, if our entered path was faulty in any other way, say we entered the name of the wrong directory when trying to access a certain file, then the result would also be a FileNotFoundeError
. This would happen even if we'd specified the mode. See a Thonny example below.
USING TRY-EXCEPT BLOCKS TO CATCH EXCEPTIONS
Here is an example of handling a FileNotFoundError
:
try: file = open('wrong_path.txt') content = file.read() except FileNotFoundError: print("Sorry, the file does not exist.") exit()
In this example, if wrong_path.txt
does not exist, Python raises a FileNotFoundError
. The except block catches this exception, outputs feedback regarding the issue to the user and then gracefully exits the program.
< previous | Table of Contents | järgmine > |