9.8 Handling Exceptions

Various types of exceptions can occur when you work with files, including:

  • A FileNotFoundError occurs if you attempt to open a non-existent file for reading with the 'r' or 'r+' modes.

  • A PermissionsError occurs if you attempt an operation for which you do not have permission. This might occur if you try to open a file that your account is not allowed to access or create a file in a folder where your account does not have permission to write, such as where your computer’s operating system is stored.

  • A ValueError (with the error message 'I/O operation on closed file.') occurs when you attempt to write to a file that has already been closed.

9.8.1 Division by Zero and Invalid Input

Let’s revisit two exceptions that you ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.