PermissionError
PermissionError is a built-in exception and a subclass of OSError that is raised when an operation runs without adequate access rights, most commonly when accessing a file or directory without the necessary filesystem 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:
- Working With Python's Built-in Exceptions (Course)
- Python's pathlib Module: Taming the File System (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Raising and Handling Python Exceptions (Course)
- How to Catch Multiple Exceptions in Python (Tutorial)
- Reading and Writing Files in Python (Guide) (Tutorial)
- Working With Files in Python (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using Python's pathlib Module (Course)
- Python's pathlib Module: Taming the File System (Quiz)
- Introduction to Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Practical Recipes for Working With Files in Python (Course)
- Working With Files in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.