PermissionError
PermissionError
is a built-in exception that is raised when an operation attempts to access a file or directory without the necessary permissions. This typically occurs when trying to read, write, or execute a file that you don’t have the rights to access.
Handling this exception is especially relevant when your code interacts with the file system, as permission issues are common.
PermissionError
Occurs When
- Trying to write to a read-only file
- Attempting to delete a file without the necessary permissions
- Trying to execute a script or program without execute permissions
- Accessing a system file that requires elevated privileges
PermissionError
Example
An example of when the exception appears:
>>> with open("/etc/hosts", mode="w") as file:
... file.write("127.0.0.1 localhost")
...
Traceback (most recent call last):
...
PermissionError: [Errno 13] Permission denied: '/etc/hosts'
An example of how to handle the exception:
>>> try:
... with open("/etc/hosts", mode="w") as file:
... file.write("127.0.0.1 localhost")
... except PermissionError:
... print("You don't have the necessary permissions.")
...
You don't have the necessary permissions.
You typically won’t raise PermissionError
manually.
Related Resources
Tutorial
Python's Built-in Exceptions: A Walkthrough With Examples
In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.
For additional information on related topics, take a look at the following resources:
- Reading and Writing Files in Python (Guide) (Tutorial)
- Working With Files in Python (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Practical Recipes for Working With Files in Python (Course)