Error permission denied errno 13 permission denied

We get PermissionError: [Errno 13] Permission denied if the Python have insufficient permissions on the file or if we pass a folder path instead of file.
Table of Contents
Hide
  1. What is PermissionError: [Errno 13] Permission denied error?
  2. How to Fix PermissionError: [Errno 13] Permission denied error?
    1. Case 1: Insufficient privileges on the file or for Python
    2. Case 2: Providing the file path
    3. Case 3: Ensure file is Closed
  3. 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. 

  1. Insufficient privileges on the file or for Python
  2. Passing a folder instead of file
  3. 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.

Avatar Of Srinivas Ramakrishna

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.

Python can only open, read from, and write to files if an interpreter has the necessary permissions. If you try to open, read from, or write to a file over which Python has no permissions, you’ll encounter the PermissionError: [errno 13] permission denied error.

In this guide, we discuss what this error means and why it is raised. We’ll walk through an example so you can learn exactly how to solve this error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

PermissionError: [errno 13] permission denied

Computers use file permissions to protect the integrity of files. Some files have restricted access by default. You can change the access permissions of a file at any time.

Let’s say you are working on an important program. You may only want that program to be readable by you. To accomplish this, you could modify the “read” permissions on all the files and folders in your program. This would limit access to your program.

Any file that you try to access from a Python program must be readable by the user or group that is running the file.

If you are running a Python script from a web server process, for instance, you would need to make sure that the user that owns the web server has access to all the files that you reference in your code.

An Example Scenario

We’re going to build a program that reads a list of NFL scores from a file into a program.

We have a file called afc_east.csv which contains the following:

Bills,4,0
Patriots,2,1
Dolphins,1,3
Jets,0,4

Our file is a CSV. We’re going to import the Python csv module into our code so we can work with the file:

Next, let’s open up our file in our Python program. We can do this using the csv.reader() statement:

with open("afc_east.csv", "r") as file:
	reader = csv.reader(file)
	for r in reader:
		print(r)

This code will open up the file called afc_east.csv in read mode. Then, the CSV reader will interpret the file. The CSV reader will return a list of values over which we can iterate. We then print each of these values to the console using a for loop and a print() statement so we can see the contents of our file line-by-line.

Let’s run our program to see if it works:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
	with open("afc_east.csv", "r") as file:
PermissionError: [Errno 13] Permission denied: 'afc_east.csv'

Our code returns an error.

The Solution

A PermissionError indicates that Python does not have the right permissions to access a file.

Let’s check the permissions of our file. We can do this using the ls -la command:

We can see that the afc_east.csv file is owned by the root user:

-rw-rw-rw-  1 root  staff  46 Oct  5 07:01 afc_east.csv

This is a problem because we don’t run Python as root. This means that Python cannot read our file. To fix this error, we need to change the ownership permissions of our file using the chown command:

chown james:admin afc_east.csv

This command makes the “james” user and the “admin” group the owners of the file.

Alternatively, we could change the permissions of the file using the chmod command:

This command makes our file readable and executable by everyone. The file is only writable by the owner. Let’s try to run our Python script again:

['Bills', '4', '0']
['Patriots', '2', '1']
['Dolphins', '1', '3']
['Jets', '0', '4']

Our code successfully prints out all of the scores from our file.

Conclusion

The PermissionError: [errno 13] permission denied error occurs when you try to access a file from Python without having the necessary permissions.

To fix this error, use the chmod or chown command to change the permissions of the file so that the right user and/or group can access the file. Now you have the skills you need to solve this error like a pro!

Table of Contents
Hide
  1. What is permission denied error?

    1. How these permissions are defined?
  2. Reasons of permissionerror ERRNO 13 in Python

    1. Using folder path instead of file path while opening a file
    2. Trying to write to a file which is a folder
    3. Trying to write to a file which is already opened in an application
    4. File permission not allowing python to access it
    5. File is hidden with hidden attribute
  3. Conclusion

    1. 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 –

  1. Using folder path instead of file path while opening a file.
  2. Trying to write to a file which is a folder.
  3. Trying to write to a file which is already opened in an application.
  4. File permission not allowing python to access it.
  5. 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 –

file permissions and setting group and owner

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.

How to troubleshoot the Permission denied Errno 13 Ansible fatal error and workaround the problem using the privilege escalation on Ansible Playbook.

February 22, 2022

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons

Today we’re going to talk about Ansible troubleshooting, specifically about permission denied [Errno 13].
I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

The Best Resources For Ansible

Video Course

  • Learn Ansible Automation in 250+examples & practical lessons: Learn Ansible with some real-life examples of how to use the most common modules and Ansible Playbook

Printed Book

  • Ansible For VMware by Examples: A Step-by-Step Guide to Automating Your VMware Infrastructure

eBooks

  • Ansible by Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps
  • Ansible For Windows By Examples: 50+ Automation Examples For Windows System Administrator And DevOps
  • Ansible For Linux by Examples: 100+ Automation Examples For Linux System Administrator and DevOps
  • Ansible Linux Filesystem By Examples: 40+ Automation Examples on Linux File and Directory Operation for Modern IT Infrastructure
  • Ansible For Containers and Kubernetes By Examples: 20+ Automation Examples To Automate Containers, Kubernetes and OpenShift
  • Ansible For Security by Examples: 100+ Automation Examples to Automate Security and Verify Compliance for IT Modern Infrastructure
  • Ansible Tips and Tricks: 10+ Ansible Examples to Save Time and Automate More Tasks
  • Ansible Linux Users & Groups By Examples: 20+ Automation Examples on Linux Users and Groups Operation for Modern IT Infrastructure
  • Ansible For PostgreSQL by Examples: 10+ Examples To Automate Your PostgreSQL database
  • Ansible For Amazon Web Services AWS By Examples: 10+ Examples To Automate Your AWS Modern Infrastructure

demo

How to troubleshoot the Ansible fatal error[Errno 13] Permission denied and fix in Ansible Playbook code.

error code

---
- name: set environment demo
  hosts: all
  gather_facts: false
  vars:
    os_environment:
      - key: EDITOR
        value: vi
  tasks:
    - name: customize /etc/environment
      ansible.builtin.lineinline:
        dest: "/etc/environment"
        state: present
        regexp: "^{{ item.key }}="
        line: "{{ item.key }}={{ item.value }}"
      with_items: "{{ os_environment }}"

error execution

ansible-pilot $ ansible-playbook -i virtualmachines/demo/inventory troubleshooting/permissiondenied_error.yml
PLAY [set environment demo] ***********************************************************************
TASK [customize /etc/environment] *****************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: PermissionError: [Errno 13] Permission denied: b'/home/devops/.ansible/tmp/ansible-tmp-1645543127.772594-89712-144540003805636/tmpvhoh4q83' -> b'/etc/environment'
failed: [demo.example.com] (item={'key': 'EDITOR', 'value': 'vi'}) => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"}, "ansible_loop_var": "item", "changed": false, "item": {"key": "EDITOR", "value": "vi"}, "msg": "The destination directory (/etc) is not writable by the current user. Error was: [Errno 13] Permission denied: b'/etc/.ansible_tmp_hwdwg3denvironment'"}
PLAY RECAP ****************************************************************************************
demo.example.com           : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
ansible-pilot $

fix code

---
- name: set environment demo
  hosts: all
  gather_facts: false
  become: true
  vars:
    os_environment:
      - key: EDITOR
        value: vi
  tasks:
    - name: customize /etc/environment
      ansible.builtin.lineinline:
        dest: "/etc/environment"
        state: present
        regexp: "^{{ item.key }}="
        line: "{{ item.key }}={{ item.value }}"
      with_items: "{{ os_environment }}"

fix execution

ansible-pilot $ ansible-playbook -i virtualmachines/demo/inventory troubleshooting/permissiondenied_fix.yml
PLAY [set environment demo] ***********************************************************************
TASK [customize /etc/environment] *****************************************************************
changed: [demo.example.com] => (item={'key': 'EDITOR', 'value': 'vi'})
PLAY RECAP ****************************************************************************************
demo.example.com           : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

code with ❤️ in GitHub

Recap

Now you know better how to troubleshoot the Ansible[Errno 13] Permission denied error.
Subscribe to the YouTube channel, Medium, Website, Twitter, and Substack to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Donate

Want to keep this project going? Please donate

Понравилась статья? Поделить с друзьями:
  • Error page text
  • Error page not found the requested url was not found on this server
  • Error page jsp
  • Error page jsf
  • Error page cannot be displayed please contact your service provider for more details перевод