Table of Contents
Hide
- What is PermissionError: [Errno 13] Permission denied error?
- How to Fix PermissionError: [Errno 13] Permission denied error?
- Case 1: Insufficient privileges on the file or for Python
- Case 2: Providing the file path
- Case 3: Ensure file is Closed
- Conclusion
If we provide a folder path instead of a file path while reading file or if Python does not have the required permission to perform file operations(open, read, write), you will encounter PermissionError: [Errno 13] Permission denied error
In this article, we will look at what PermissionError: [Errno 13] Permission denied error means and how to resolve this error with examples.
We get this error mainly while performing file operations such as read, write, rename files etc.
There are three main reasons behind the permission denied error.
- Insufficient privileges on the file or for Python
- Passing a folder instead of file
- File is already open by other process
How to Fix PermissionError: [Errno 13] Permission denied error?
Let us try to reproduce the “errno 13 permission denied” with the above scenarios and see how to fix them with examples.
Case 1: Insufficient privileges on the file or for Python
Let’s say you have a local CSV file, and it has sensitive information which needs to be protected. You can modify the file permission and ensure that it will be readable only by you.
Now let’s create a Python program to read the file and print its content.
# Program to read the entire file (absolute path) using read() function
file = open("python.txt", "r")
content = file.read()
print(content)
file.close()
Output
Traceback (most recent call last):
File "C:/Projects/Tryouts/python.txt", line 2, in <module>
file = open("python.txt", "r")
PermissionError: [Errno 13] Permission denied: 'python.txt'
When we run the code, we have got PermissionError: [Errno 13] Permission denied error because the root user creates the file. We are not executing the script in an elevated mode(admin/root).
In windows, we can fix this error by opening the command prompt in administrator mode and executing the Python script to fix the error. The same fix even applies if you are getting “permissionerror winerror 5 access is denied” error
In the case of Linux the issue we can use the sudo
command to run the script as a root user.
Alternatively, you can also check the file permission by running the following command.
ls -la
# output
-rw-rw-rw- 1 root srinivas 46 Jan 29 03:42 python.txt
In the above example, the root user owns the file, and we don’t run Python as a root user, so Python cannot read the file.
We can fix the issue by changing the permission either to a particular user or everyone. Let’s make the file readable and executable by everyone by executing the following command.
chmod 755 python.txt
We can also give permission to specific users instead of making it readable to everyone. We can do this by running the following command.
chown srinivas:admin python.txt
When we run our code back after setting the right permissions, you will get the following output.
Dear User,
Welcome to Python Tutorial
Have a great learning !!!
Cheers
Case 2: Providing the file path
In the below example, we have given a folder path instead of a valid file path, and the Python interpreter will raise errno 13 permission denied error.
# Program to read the entire file (absolute path) using read() function
file = open("C:\Projects\Python\Docs", "r")
content = file.read()
print(content)
file.close()
Output
Traceback (most recent call last):
File "c:PersonalIJSCodeprogram.py", line 2, in <module>
file = open("C:\Projects\Python\Docs", "r")
PermissionError: [Errno 13] Permission denied: 'C:\Projects\Python\Docs'
We can fix the error by providing the valid file path, and in case we accept the file path dynamically, we can change our code to ensure if the given file path is a valid file and then process it.
# Program to read the entire file (absolute path) using read() function
file = open("C:\Projects\Python\Docspython.txt", "r")
content = file.read()
print(content)
file.close()
Output
Dear User,
Welcome to Python Tutorial
Have a great learning !!!
Cheers
Case 3: Ensure file is Closed
While performing file operations in Python, we forget to close the file, and it remains in open mode.
Next time, when we access the file, we will get permission denied error as it’s already in use by the other process, and we did not close the file.
We can fix this error by ensuring by closing a file after performing an i/o operation on the file. You can read the following articles to find out how to read files in Python and how to write files in Python.
Conclusion
In Python, If we provide a folder path instead of a file path while reading a file or if the Python does not have the required permission to perform file operations(open, read, write), you will encounter PermissionError: [Errno 13] Permission denied error.
We can solve this error by Providing the right permissions to the file using chown
or chmod
commands and also ensuring Python is running in the elevated mode permission.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Table of Contents
Hide
-
What is permission denied error?
- How these permissions are defined?
-
Reasons of permissionerror ERRNO 13 in Python
- Using folder path instead of file path while opening a file
- Trying to write to a file which is a folder
- Trying to write to a file which is already opened in an application
- File permission not allowing python to access it
- File is hidden with hidden attribute
-
Conclusion
- Related Posts
Permission denied means you are not allowed to access a file. But why this happens? This is because a file has 3 access properties – read, write, and execute. And 3 sets of users – owner, group, and others. In this article we will look at different solutions to resolve PermissionError: [Errno 13] Permission denied.
What is permission denied error?
Suppose you have a file in your computer but you can’t open it. Strangely another user can open the same file. This is because you don’t have permission to read the content of that file.
Permission denied on files to protect them. For example, you have stored username & password for your database in a file so you never want it to be accessible to anyone except the database application and you. That’s why you will restrict it from other applications, software, processes, users, APIs etc.
In a system, root user can access everything. So, we seldom use the root account otherwise there is no meaning of security. A software running with root privilege can access your password file which you wanted to be secure. That’s why sudo
should be used with caution.
How these permissions are defined?
There are 3 types of permissions – read, write and execute. With read permission a software, process, application, user etc. can read a file. Similarly, with write permission they can write to the file. Execute is used to run it.
Now the question is, how to apply these permissions to different software, users etc.? Well there are 3 types of users – owner, group, and others. So, you can assign 3 sets of permissions, like this –
User | Description | Permissions |
---|---|---|
Owner | An account of system who we want to separately assign permissions | r – read w – write x – execute |
Group | A set of multiple accounts, software, processes who can share the same permissions | r – read w – write x – execute |
Others | All the other entities of system | r – read w – write x – execute |
Let’s get back to our password file example. Now you are into others
user category because you are not the owner of the file and probably not the part of group. People use to give least permissions to the others
because these are the access levels for everyone.
The password file won’t have any permission in others
category. And trying to access that will result in permission error: permission denied.
Reasons of permissionerror ERRNO 13 in Python
Primarily these are the reasons of permissionerror: errno13 permission denied in Python –
- Using folder path instead of file path while opening a file.
- Trying to write to a file which is a folder.
- Trying to write to a file which is already opened in an application.
- File permission not allowing python to access it.
- File is hidden with hidden attribute.
Let’s understand each of these reasons one by one and check their solutions.
Using folder path instead of file path while opening a file
To open a file for reading or writing, you need to provide the absolute or relative path to the file in open
function. Sometimes we create path of parent folder instead of file and that will lead to the permission error 13. Check out this code –
file = open("C:\users\akash\Python\Documents", "r") file.close()
The output will be –
Traceback (most recent call last): File "jdoodle.py", line 2, in <module> file = open("C:\users\akash\Python\Documents", "r") PermissionError: [Errno 13] Permission denied: 'C:\users\akash\Python\Documents'
The reason for the error in above code is that we have used C:usersakashPythonDocuments
as path which is a directory. Instead we needed to use C:usersakashPythonDocuments\myFile.csv
.
Trying to write to a file which is a folder
This is a common case. Suppose you want to write to a file using Python but a folder with same name exists at that location then Python will get confused and try to write to a folder. This is not a right behavior because folders are not files and you can’t write anything on them. They are used for holding files only.
Trying to write to a file which is a folder will lead to permission error errno 13. Check this code –
# Directory Structure # 📂/ # |_ 📂Users # |_ 📁myFile file = open("/Users/myFile", "w") file.write("hello") file.close()
The output will be –
Traceback (most recent call last): File "jdoodle.py", line 2, in <module> file = open("/Users/myFile", "r") PermissionError: [Errno 13] Permission denied: '/Users/myFile'
In the above example we showed the directory structure and tried to write to myFile
. But myFile
is already a name of directory in the path. Generally, if a file doesn’t exist and we try to write to it then Python creates the file for us. But in this case there is already a directory with the provided name and Python will pick it. This will lead to permission error.
The solution to this problem is to either delete the conflicting directory or use a different file name.
Trying to write to a file which is already opened in an application
If a file is already opened in an application then a lock is added to it so that no other application an make changes to it. It depends on the applications whether they want to lock those files or not.
If you try to write to those files or more, replace, delete them then you will get permission denied error.
This is very common in PyInstaller if you open a command prompt or file explorer inside the dist folder, then try to rebuild your program. PyInstaller wants to replace the contents of dist but it’s already open in your prompt/explorer.
The solution to this problem is to close all the instances of applications where the file is opened.
File permission not allowing python to access it
In the above section we talked about file permissions. Python will be in others category if it is not set as user or in a group. If the file has restrictive permissions for others then Python won’t be able to access it.
Suppose the permission to the file is –
Owner – read, write, execute
Group – read, write
Others – none
Then only owner and group will be able to read and write to the file. Others will not be able to access it. Check out this image –
In this image the file owner is www, group is www, owner permissions are read+write, group permission is read only, while others have no permissions.
The solution to this problem is to either provide appropriate permission to the file for others, or add Python as owner or to the group.
Another solution is to run Python with root privilege.
File is hidden with hidden attribute
If your file is hidden then python will raise permission error. You can use subprocess.check_call() function to hide/unhide files. Check this code –
import subprocess myPath = "/Users/myFile.txt" subprocess.check_call(["attrib", "-H", myPath]) file_ = open(myPath, "w")
In the above code -H
attribute is used to unhide the file. You an use +H
to hide it again.
Conclusion
In this article we saw a number of reasons for Python to throw PermissionError: [Errno 13] Permission denied and discussed about their solutions with code examples. Follow the steps provided in article and you will be able to resolve this issue.
Detseus 0 / 0 / 0 Регистрация: 18.04.2020 Сообщений: 49 |
||||||||
1 |
||||||||
05.05.2020, 19:31. Показов 16048. Ответов 6 Метки нет (Все метки)
Выскакивает ошибка
Мой код
Что я сделал не так?
__________________
0 |
Автоматизируй это! 6485 / 4178 / 1140 Регистрация: 30.03.2015 Сообщений: 12,334 Записей в блоге: 29 |
|
05.05.2020, 21:17 |
2 |
Что я сделал не так? зачем создавать что-то на рабочем столе? ты еще в паке винды начни экспериментировать создай отдельную папку на диске (не рабочий стол и никакой кириллицы) и все проекты делай там
0 |
0 / 0 / 0 Регистрация: 18.04.2020 Сообщений: 49 |
|
05.05.2020, 21:29 [ТС] |
3 |
зачем создавать что-то на рабочем столе? ты еще в паке винды начни экспериментировать создай отдельную папку на диске (не рабочий стол и никакой кириллицы) и все проекты делай там В этом вся проблема, да?
0 |
Автоматизируй это! 6485 / 4178 / 1140 Регистрация: 30.03.2015 Сообщений: 12,334 Записей в блоге: 29 |
|
05.05.2020, 21:37 |
4 |
В этом вся проблема, да? это может быть причиной
0 |
0 / 0 / 0 Регистрация: 18.04.2020 Сообщений: 49 |
|
05.05.2020, 21:38 [ТС] |
5 |
это может быть причиной А так в коде ошибки нет в самом? Что то стоит подправить?
0 |
unfindable_404 683 / 466 / 204 Регистрация: 22.03.2020 Сообщений: 1,051 |
||||
05.05.2020, 22:47 |
6 |
|||
Решение
А так в коде ошибки нет в самом? Есть. На 4 строке ты создаёшь папку с именем «Result».
0 |
Detseus 0 / 0 / 0 Регистрация: 18.04.2020 Сообщений: 49 |
||||
05.05.2020, 22:49 [ТС] |
7 |
|||
Есть. На 4 строке ты создаёшь папку с именем «Result».
Даа так, ЛУУУУУУУУУУУЧШИЙ!
0 |