Python ошибка доступа

I am trying to call a python program with subprocess, but I get a permission error. I tried running PyCharm as an admin, but it doesn’t help.

My code:

answer = subprocess.check_output("../folder python program %s %s" %(valueA, valueB), encoding = 'utf8')

The error:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/a/b/b_resolution.py", line 35, in <module>
    answer = subprocess.check_output("../folder python program %s %s" %(valueA, valueB), encoding = 'utf8')
  File "C:UsersUserAppDataLocalProgramsPythonPython37-32Libsubprocess.py", line 376, in check_output
    **kwargs).stdout
  File "C:UsersUserAppDataLocalProgramsPythonPython37-32Libsubprocess.py", line 453, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:UsersUserAppDataLocalProgramsPythonPython37-32Libsubprocess.py", line 756, in __init__
    restore_signals, start_new_session)
  File "C:UsersUserAppDataLocalProgramsPythonPython37-32Libsubprocess.py", line 1155, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access Denied

Does someone know how I can fix this permission error?

The permissionerror: [winerror 5] access is denied is a very common bug that occurs when you use Python on Windows. As a python developer, you must have run into this error at least once because of how easily it can occur.Permissionerror Winerror 5 Access Is Denied

This error can be resolved in an easy and quick way. In this article, we take you through the error, the reason behind its occurring, and five simple ways to solve it.

Contents

  • Why Does the Permissionerror: [Winerror 5] Access Is Denied Occurs?
    • – Permissionerror: [winerror 5] Access Is Denied in Tesseract
    • – Permissionerror: [winerror 5] Access Is Denied in Jupyter Notebook
    • – Permissionerror: [winerror 5] Access Is Denied in VSCode
  • How to Resolve the permissionerror: [winerror 5] access is denied in Python?
    • – Run the Code As Administrator
    • – Upgrade or Reinstall Python
    • – Make Sure Your File Has Open Access
    • – Check Your Working Directory
    • – Check Your Script
  • FAQ
    • 1. How To Solve Access Is Denied Python OS Remove?
    • 2. What Is the Simplest Way To Fix Access Denied Error?
  • Conclusions

Why Does the Permissionerror: [Winerror 5] Access Is Denied Occurs?

The main reason behind the permissionerror: [winerror 5] access is denied in Python while running on Windows is that you are only allowed to run programs and not directories. This error is can occur when you are trying to open an application in Python or running a script.

Using Python on Windows can be painful sometimes when a code would just throw errors like permissionerror: [winerror 5] access is denied and you cannot do anything about it. There can be various reasons why this error is showing up as it used to work fine before but this time it is giving a persistent error.

It can show up when you are trying to access your directory, perform a task that goes beyond your current programming tool, or simply try to open software that is outdated or needs to be upgraded. The possibilities can be many.

Now that we know what might be causing this error, we must look at the error line itself. A permission error occurs when you do not have permission to access or perform a certain task. That right is reserved chiefly with the administrator only. A win error is any error that defines a system error and mostly goes away by updating the software or uninstalling and reinstalling it.

– Permissionerror: [winerror 5] Access Is Denied in Tesseract

The permissionerror: (winerror 5) access is denied tesseract is a very common error. Tesseract is an open-source optical character/text recognition (OCR) engine that can extract text from files and images and makes them into a new searchable file of any format of choice. It is therefore very popular among web and software developers.

The error when encountered in Tesseract means that either the file you are trying to reach is in another directory or you do not have permission to perform the said error. In both cases, the error can be fixed. Tesseract is not only used in Python but also in various coding languages.Permissionerror Winerror 5 Access Is Denied Variations

– Permissionerror: [winerror 5] Access Is Denied in Jupyter Notebook

This platform is another example of the error: permissionerror: (winerror 5) access is denied jupyter notebook and it occurs because you are not allied access to the file. Jupyter notebook is a very famous platform for running Python and it is used heavily. The error can thus be very easily resolved.

– Permissionerror: [winerror 5] Access Is Denied in VSCode

Visual Studio Code is a free source code engine that supports a lot of languages including Python. While using it, you may encounter the permissionerror: (winerror 5) access is denied jupyter notebook.

Like the above errors in platforms, the same error can be encountered as permissionerror: (winerror 5) access is denied-selenium, permissionerror: (winerror 5) access is denied chrome driver, and permissionerror: (winerror 5) access is denied pycharm.

How to Resolve the permissionerror: [winerror 5] access is denied in Python?

You can solve the error by either running the code as the administrator, upgrading or reinstalling python, making sure that your file has open access, and lastly by checking your working directory and script for any hidden errors or mistakes.



We now know that the error occurs because you might be running directories when you can only run programs. It is a Python error and we have complete solutions to it. We have discussed multiple solutions based on the cause of the error so don’t miss any of them.

– Run the Code As Administrator

Most times the easiest way to get rid of the permission error is by running it as an administrator. We know that the error occurs because you do not have access to the directory, or files, or basically cannot perform that task. An administrator has full control and access to perform any task and run any file or directory.

For this, go to the settings of whatever platform you are using and you should be able to find the administrator setting. After running the code as administrator, there should be no problem at all if the whole error was because of the access issue. If the error occurs still, try the following pointers.

– Upgrade or Reinstall Python

Another way to resolve this permission error is by updating your Python by pip install. Most times, the new updates have updated codes which renders the old ones useless. They might be working just fine for you but with the new update, you might want to use the new ones.

Reinstalling Python after uninstalling it may also work for your error. It will ensure that there is no issue with upgrading it and also if there was, the new installation would have taken care of it. This resolution works best for the people who claim that the code was working just fine before and now there seems to be a problem.Permissionerror Winerror 5 Access Is Denied Fixes

Version 3.7.2 was a buggy version of Python. It may be working fine in some instances but make sure to update it to 3.7.3 which is a way better version with fewer bugs.

– Make Sure Your File Has Open Access

We might be faulting the administrator issues or the version of Python but sometimes the error is only because the file does not have open access. It may be locked or encrypted or simply inaccessible. For this reason, whenever the error shows up, ensure the file you are trying to access is open and present. Check if the file is not broken and active.

This will surely help in diagnosing the real problem behind the error and help in swift resolution. In this case, there is no need to run it as the administrator or even upgrade your Python package.

– Check Your Working Directory

Sometimes the error might occur because of the error in your working directory path. While working on Pycharm or certain other platforms, it is most likely that at the start your working directory path is not set. This will prompt the error for sure. For this reason, it is best to set the file path to your project so that everything can be found in one place and run smoothly.

– Check Your Script

The last and the most obvious resolution to the problem is to check your script if any of the above pointers are missing in it. It may be not visible at first but trust me, it will be. Take your time to fully understand what is going on and then diagnose the problem. We have given you all five solutions here and they should surely help you in getting your code to work.

FAQ

1. How To Solve Access Is Denied Python OS Remove?

You can solve permissionerror: [winerror 5] access is denied python OS remove by deleting the files in the directory before deleting the directory itself. You may be getting this error because you are attempting to delete a directory and the file of that directory is still in use somewhere.

So deleting the files and making sure that they are not being used anywhere else is a good way to start and get the work done.

2. What Is the Simplest Way To Fix Access Denied Error?

The simplest way to fix the access denied error is by editing the permissions of any file to your name. You can access the properties of any file and click on security tab where you can change the permissions. There are other solutions as well but they are relatively complex.

Conclusions

In this article, we talked about the permissionerror: [winerror 5] access is denied. The error is a commonly occurring error in Python and its platforms. It is however very easy to solve and you can make your code run in no time because most times it is an error of access and sometimes the platform. Following are the points that will summarize the article so that there’s no confusion left:

  • The main reason behind the permissionerror: [winerror 5] access is denied in Python while running on Windows is that you are only allowed to run programs and not directories or that the program is faulty or the file cannot be accessed.
  • The easiest way to get rid of the error is to run it as an administrator. It should clear up your error and give you access to all the files and functions.
  • Upgrading and updating your Python package might also work best.
  • As this code is very common, it may occur in any platform using and running Python like Pycharm, VScode, Tesseract, and many more.

We believe that this guide is all that you will need to detect the causes of this error and fix them in a timely manner.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

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.

TL;DR: python -m pip install -U pip, then try again.


I was already using a venv (virtualenv) in PyCharm.

Creating it I clicked inherit global site packages checkbox, to allow packages installed via an installer to work.
Now inside my venv there was no pip installed, so it would use the inherited global pip.

Here is how the error went:

(venv) D:pathtomyproject> pip install certifi  # or any other package

Would fail with

PermissionError: [WinError 5] Access denied: 'c:\program files\python36\Lib\site-packages\certifi'

Notice how that is the path of the system python, not the venv one.
However we want it to execute in the right environment.

Here some more digging:

(venv) D:pathtomyproject> which pip
/c/Program Files/Python36/Scripts/pip

(venv) D:pathtomyproject> which python
/d/path/to/my/project/venv/Scripts/python

So python is using the correct path, but pip is not?
Let’s install pip here in the correct one as well:

(venv) D:pathtomyproject> python -m pip install -U pip
... does stuff ...
Successfully installed pip

Now that’s better.
Running the original failing command again now works, as it is using the correct pip.

(venv) D:pathtomyproject> pip install certifi  # or any other package
... install noise ...
Successfully installed certifi-2019.9.11 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.7

Taking a shot in the dark here and hoping someone can point me in the right direction as to why I’m getting this error. I have used this same script in the past without issue so I’m completely lost as to what happened. Any help/suggestions would be greatly appreciated.

from requests_html import HTMLSession

link = 'https://www.denvergov.org/property/realproperty/summary/160820474'
session = HTMLSession()
url = session.get(link)
print(url)

<Response [200]>

url.html.render()

Traceback (most recent call last):
  File "C:/Users/Nick/gfddfsf.py", line 9, in <module>
    url.html.render()
  File "C:UsersNicklibsite-packagesrequests_html.py", line 572, in render
    self.session.browser  # Automatycally create a event loop and browser
  File "C:UsersNicklibsite-packagesrequests_html.py", line 680, in browser
    self._browser = self.loop.run_until_complete(pyppeteer.launch(headless=True, args=['--no-sandbox']))
  File "C:UsersNicklibasynciobase_events.py", line 467, in run_until_complete
    return future.result()
  File "C:UsersNicklibsite-packagespyppeteerlauncher.py", line 311, in launch
    return await Launcher(options, **kwargs).launch()
  File "C:UsersNicklibsite-packagespyppeteerlauncher.py", line 169, in launch
    **options,
  File "C:UsersNicklibsubprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "C:UsersNicklibsubprocess.py", line 997, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access is denied

The “PermissionError: [winerror 5] access is denied or the Winerror 5 access is denied” issue is a very common error message that appears while using python on Windows. Almost all of the python developers encounter this error message on some stage of their coding.  This error might appear while they are importing python on some programming tool or it might appear while running a script. In this article, we have compiled some solutions to rectify the “[WinError 5] Access is denied” error completely from Python.

[winerror 5] access is denied Error on Python

Error Message

What Causes the Access is Denied Error?

The main reason behind the error of access denial is that you are only allowed to run programs and not directories. This error will occur if we try to run a directory.

This error can occur due to incorrect syntax of the code or any older version of the Python.

What to do if you get the “winerror 5 access is denied” Message in CMD or Python?

1. Solution 1: Run as Administrator

If you are trying to install python directories from your command prompt and the “winerror 5 access is denied” error appears then there is nothing to worry about. This error can be solved very easily and quickly. Just follow the steps below to resolve this issue

  1. Click on the search button in the taskbar and type “cmd”. Right-click on the Command Prompt and select Run as Administrator.
    Running Command Prompt as Administrator
    Command Prompt
  2. Write the following command and press “Enter”.
    pip install pydirectory

    Running the "pip install pydirectory" command in the command Prompt

    Command
  3. Check if this error appears again.

2.Solution 2: Set Permission

Sometimes syntax used for different versions of python can be the reason behind this error. For example, if you wanted to set permission for python 2, the command used was as follows

os.chmod('spam.txt', 777)

This will be considered wrong if you are using python 3 because this syntax is outdated and will lead to a syntax error. The syntax used to access permission in python 3 is a little bit different. The command for python 3 is as follows.

os.chmod('spam.txt', 0o777)

3. Solution 3: Give Path To The Image

If you are opening an image in your code, this error might occur because of the wrong syntax. You will get this permission denial if you write the code in the following syntax

img = cv2.imread('G:/project/OCR/FDA.png')

This issue an be resolved by adding an “r” before the path of the image. For example, the correct syntax of the code which will not cause any error will be as follows.

img = cv2.imread(r'G:/project/OCR/FDA.png')

4. Solution 4: Update Python

Sometimes this error arises due to an old version of Python. The latest version of python has all the updates and fixes of the bugs that were present in the older versions. If you are using version 3.7.2 of python then make sure you update it to version 3.7.3 because the older version contains some bugs which might be the reason behind this error.

If you need further assistance, contact here. You can also seek help from the official Python page.

Photo of Alan Adams

Alan is a hardcore tech enthusiast that lives and breathes tech. When he is not indulged in playing the latest video games, he helps users with technical problems that they might run into. Alan is a Computer Science Graduate with a Masters in Data Science.

Python responds with PermissionError: [Errno 13] Permission denied message when you try to open a file with the following exceptions:

This article will help you to resolve the issues above and fix the PermissionError message.

You specify a path to a directory instead of a file

When you call the open() function, Python will try to open a file so that you can edit that file.

The following code shows how to open the output.txt file using Python:

with open('text_files/output.txt', 'w') as file_obj:
    file_obj.write('Python is awesome')

While opening a file works fine, the open() function can’t open a directory.

When you forget to specify the file name as the first argument of the open() function, Python responds with a PermissionError.

The code below:

with open('text_files', 'w') as file_obj:

Gives the following output:

Because text_files is a name of a folder, the open() function can’t process it. You need to specify a path to one file that you want to open.

You can write a relative or absolute path as the open() function argument.

An absolute path is a complete path to the file location starting from the root directory and ending at the file name.

Here’s an example of an absolute path for my output.txt file below:

abs_path = "/Users/nsebhastian/Desktop/DEV/python/text_files/output.txt"

When specifying a Windows path, you need to add the r prefix to your string to create a raw string.

This is because the Windows path system uses the backslash symbol to separate directories, and Python treats a backslash as an escape character:

# Define a Windows OS path
abs_path = r"DesktopDEVpythontext_filesoutput.txt"

Once you fixed the path to the file, the PermissionError message should be resolved.

The file is already opened elsewhere (in MS Word or Excel, .etc)

Microsoft Office programs like Word and Excel usually locked a file as long as it was opened by the program.

When the file you want to open in Python is opened by these programs, you will get the permission error as well.

See the screenshot below for an example:

To resolve this error, you need to close the file you opened using Word or Excel.

Python should be able to open the file when it’s not locked by Microsoft Office programs.

You don’t have the required permissions to open the file

Finally, you will see the permission denied error when you are trying to open a file created by root or administrator-level users.

For example, suppose you create a file named get.txt using the sudo command:

The get.txt file will be created using the root user, and a non-root user won’t be able to open or edit that file.

To resolve this issue, you need to run the Python script using the root-level user privilege as well.

On Mac or Linux systems, you can use the sudo command. For example:

On Windows, you need to run the command prompt or terminal as administrator.

Open the Start menu and search for “command”, then select the Run as administrator menu as shown below:

Run the Python script using the command prompt, and you should be able to open and write to the file.

Conclusion

To conclude, the error “PermissionError: [Errno 13] Permission denied” in Python can be caused by several issues, such as: opening a directory instead of a file, opening a file that is already open in another program, or opening a file for which you do not have the required permissions.

To fix this error, you need to check the following steps:

  1. Make sure that you are specifying the path to a file instead of a directory
  2. Close the file if it is open in another program
  3. Run your Python script with the necessary permissions.

By following these steps, you can fix the “PermissionError: [Errno 13] Permission denied” error and successfully open and edit a file in Python.

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.

  1. HowTo
  2. Python How-To’s
  3. Python PermissionError: [WinError 5] …

Rana Hasnain Khan
Nov 24, 2022

Python PermissionError: [WinError 5] Access Is Denied

We will briefly introduce how to resolve the PermissionError: [WinError 5] Access is denied in Python.

PermissionError: [WinError 5] Access is denied in Python

The PermissionError: [WinError 5] Access is denied is a very common error message that appears while using Python on Windows. This error might occur when we import Python packages, run a script, or update or install any Python packages.

Almost all python developers encounter this error at some stage in their careers. The error message is shown below.

permissionerror [winerror 5] access denied in Python

From the above image, I tried to install the setuptools using pip, and it gave me the PermissionError: [WinError 5] Access is denied. The solution is very simple, follow the steps below:

  • Go to search and write cmd, right-click on it, and run it as an administrator, as shown below.

    step 1 for solving permissionerror [winerror 5] access is denied

  • Now, we will run the command again, and it will work just fine, as shown below.

    step 2 for solving permissionerror [winerror 5] access is denied

When we run the cmd as an administrator and run the command or install or update any package, it works fine without giving any error.

Rana Hasnain Khan avatar
Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article — Python Error

  • Can Only Concatenate List (Not Int) to List in Python
  • Invalid Syntax in Python
  • Value Error Need More Than One Value to Unpack in Python
  • ValueError Arrays Must All Be the Same Length in Python
  • Fix the TypeError: Object of Type ‘Int64’ Is Not JSON Serializable
  • Fix the TypeError: ‘float’ Object Cannot Be Interpreted as an Integer in Python

Понравилась статья? Поделить с друзьями:
  • Python ошибка random
  • Python ошибка memory error
  • Python ошибка math domain error
  • Python ошибка killed
  • Python ошибка int object is not callable