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:

Python
>>> 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:

Python
>>> 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 26, 2025 • Reviewed by Martin Breuss