In this article, we’ll take a look at PermissionError in Python. We will understand what it is and what causes it. Let’s begin!
What is PermissionError?
PermissionError is simply an Exception that is raised when you try to do an operation in Python but you can’t because you do not have sufficient permissions.
From the official Python documentation:
“Raised when trying to run an operation without adequate access rights – for example, filesystem permissions.”
Since PermissionError is an exception that is involved with system operations, it is a subclass of the OSError class (to read more about the exception hierarchy with diagrams, click here).
When do we get PermissionError?
You may be getting the PermissionError in the following cases:
Working with files:
Systems have file permissions kept in place to protect the integrity of files and their contents. Python can open, read, and write to a file only when your interpreter is run as a user with the necessary permissions to access it.
This included situations such as:
- Attempting to either read from a file or write to a file you don’t have permission to access.
- Attempting to modify a file itself without sufficient permissions. (For example, the file may be owned by another user).
- Trying to open a file with a path, but the given path in your program is actually pointing to a folder. I.e. you’re reading a folder like a file.
For example, using the open() function:
with open(r"C:\Users\EI\Desktop) as my_file: #the path ends as a folder, not a file
print(my_file.read())
By default, the open() function is designed to open files in a directory. If you attempt to open a folder with it, it raises the PermissionError.
- Trying to access or open a file that is already open in some other application in Windows (For example, it may be opened in Excel).
It is designed this way to prevent conflicts when one application edits some changes and the other application can again edit or delete those changes at the same time.
Working with directories
The same PermissionError can be raised when working with directories as well. This may happen when you try to create or delete a directory in a location where your program does not have the required permissions.
External Commands
If you try to execute or run a system command that requires elevated privileges without the necessary permissions, you will raise a PermissionError.
I hope by now you have a better idea of what PermissionError means and what causes it.
And with that, let’s end this article.
Kudos to you on making it to the end of the article, not many have the patience to do so!
I hope you enjoyed reading this article and found this article helpful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Related Articles
7 Most Common In-Built Exceptions in Python!
Python: Details contained in an Exception