Fix Python PermissionError: [Errno 13] Permission denied
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:
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.
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:
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:
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.
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.
- Make sure that you are specifying the path to a file instead of a directory
- Close the file if it is open in another program
- 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.
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Handling Error 13: Permission Denied in Python
Error 13: Permission Denied in Python is an I/O error that occurs when the system cannot communicate with your code to carry out the desired operation. Causes include trying to access a nonexistent file, an already-opened file, opening a directory as a file, or having incorrect permissions. There are multiple ways to fix this error, such as closing other instances of the file, updating permissions, ensuring you’re not accessing a directory, and using try-except blocks for error handling.
The error is very simple as shown below:
An input/output error is a type of runtime error. Runtime errors are caused by wrong formats of input or when the code is unable to produce an output.
Since there are no syntax errors in the code, the Python interpreter interprets the code, compiles it, but when executing, it cannot parse particular statements or execute them.
Common Causes of I/O Errors (Permission Denied)
Input/output errors are caused by several reasons. Some of them are:
- The most common cause of an I/O error is if the file specified doesn’t exist.
- When trying to read() or open() a file, the system cannot communicate with the code if the file is already opened somewhere else.
- If you’re trying to open a directory instead of a file, but trying to open it like a file, it will raise an input/output error.
- If there is a forward slash in the path of the directory, it might also raise an i/o error.
- If you don’t have permission to open that particular file or if Python doesn’t have access to the specific directory.
There is a very thorough article on Python i/o errors on ask python, you can check it out here!
Resolving Error 13: Permission Denied in Python
There can be more than one way by which this error can be fixed. They are:
- Making sure you spell the file correctly and not using the path of a directory.
- Making sure that the permissions are updated before trying to access the file.
- The path of the file must be specified without any errors such as a forward slash.
- The file that we’re trying to open shouldn’t be opened somewhere else.
- Using a try and except block to find out where the error arises.
We’ll look at all these methods in depth one by one.
Fix 1: Close Other Instances of the File
When a particular file is opened in Microsoft excel or Microsoft word, this error frequently pops up. This happens because these applications do not let any other application modify a file when used via them.
Hence, make sure you have the files closed before trying to access them via your python code and make sure that on a windows computer no Microsoft office applications are using your file when you’re trying to open() or read() it.
Fix 2: Update Permissions and Run as Administrator
When trying to run your python script make sure you run it via the command prompt in the administrator mode.
This won’t affect your existing permissions for other applications, it will only override the Python permission for this particular script and no other. Make sure you’ve installed Python with the required PATH permissions.
When you open the command prompt, choose “run as administrator” from the right-hand panel as shown below in the picture with the red arrow.
Using Command Prompt In The Administrator Mode.
Fix 3: Ensure You Are Not Accessing a Directory
In this case, you’re trying to open a directory instead of trying to open a particular file. This problem can be fixed by specifying the absolute path of a file.
For example, if your file name is “First_program.txt” then you might as well use the command below with open() .
This helps in avoiding mistakes in specifying file names or paths and even directories.
Fix 4: Use Try and Except Blocks for Error Handling
The try and except statements can be used as well in this case. Try and except blocks are used to handle exceptions in Python. The code for the following would be:
We have an in-depth article about python exception handling. Click here to read!
Error 13: Permission Denied in Python can be addressed through various methods and understanding its causes. By applying these solutions, you can avoid hiccups in your programming journey and ensure smooth progress. Have you come across any other creative solutions or preventative measures to tackle permission errors?
PermissionError: [Errno 13] Permission denied. Что делать?
По поводу оформления:
Поместите код в блок для исходных кодов. Для этого нажмите кнопку < / > на панели и выберите Python. Оформление вопроса в таком виде, просто издевательство для глаз. В Python важны именно отступы, а у Вас все сливается
Это замечание. Сейчас попытаюсь разобраться в вопросе
Не сработало скорее всего из за того, что «\» это спец. символ. Используется для обозначения таких вещей как конец строки (\n), табуляция (\t). В Вашем случае, скорее всего пыталась понять что значит \д, \G и т.д. Для написания символа \ в строках используют \\.
В зависимости от версии Python может быть проблема и в кодировке пути. Т.к. есть различие русских символов в UTF8 и cp1251 которая используется обычно в Windows.
PermissionError: [Errno 13] Permission Denied: [Python Fix]
Try these solutions to fix PermissionError [Errno 13] Permission denied
- If Python cannot locate a file or does not have the necessary permissions to open it, then the PermissionError: [Errno 13] Permission denied error may occur.
- Release 3.7 introduced Python into the Microsoft Store which can cause permission denied errors.
- The latest version of Python is 3.10.7 and is available for macOS, Linux/UNIX, and Windows 8 or newer.
- Download and Install Fortect on your PC
- Launch the tool and Start scanning to find broken files that are causing the problems
- Right-click on Start Repair to fix issues affecting your computer’s security and performance
- Fortect has been downloaded by 0 readers this month.
Python is a program designed for building websites, software, and more using a high-level programming language. However, users have recently reported receiving a permission denied error in Windows 11. Here’s how to fix PermissionError [Errno 13] Permission denied error in Python.
Because Python uses a general-purpose language, it can be used to build a variety of different types of programs rather than focusing on a specific variable.
For those wanting to learn more about developing and coding, Python is one of the easiest programming languages to learn, making it perfect for beginners.
Why do I get the permission denied error in Python?
Users encounter PermissionError: [Errno 13] Permission denied error if providing Python with a file path that does not have permission to open or edit the file. By default, some files do not allow certain permissions. This error may also occur if providing a folder rather than a file.
If the file is already being operated by another process, then you may encounter the permission denied error in Python. If you’re receiving the Python runtime error, we offer solutions for that as well.
How do I fix the Python permission denied error in Windows 11?
1. Check file path
One of the main causes of PermissionError: [Errno 13] Permission denied is because Python is trying to open a folder as a file. Double-check the location of where you want to open the file and ensure there isn’t a folder that exists with the same name.
Run the os.path.isfile(filename) command replacing filename with your file to check if it exists. If the response is false, then the file does not exist or Python cannot locate it.
2. Allow permissions using chomd
If the file does not have read and write permissions enabled for everyone, then you may encounter the permission denied error in Python. Try entering the chomd 755 filename command and replace filename with the name of your file.
This command gives everyone permission to read, write, and execute the file, including the owner. Users can also apply this command to entire directories. Running the ls -al command will provide a list of files and directories and their permissions.
3. Adjust file permissions
- Navigate to the location of your file in file explorer.
- Right-click on the file and select Properties.
- Click the Security tab then select your name under Group or user names.
- Select Edit and go through and check permissions.
- Click Apply then OK.
Some PC issues are hard to tackle, especially when it comes to missing or corrupted system files and repositories of your Windows.
Be sure to use a dedicated tool, such as Fortect, which will scan and replace your broken files with their fresh versions from its repository.
Adjusting the permissions of the file that you’re trying to open will allow Python to read, write, and execute the file.
Read more about this topic
4. Turn off execution aliases
- Click on Start and open Settings (or press Windows + I ).
- Open Apps then select Apps & features.
- Open the drop-down menu next to More settings.
- Click App execution aliases.
- Locate the two App Installers for python.exe and python3.exe and toggle both to Off.
Python was added to the Microsoft Store for version 3.7 which introduced permission denied errors because it created two installers: python.exe and python3.exe. Disabling the Microsoft Store versions of Python should fix the permissions denied error.
5. Update Windows and drivers
- Click on Start and open Settings (or press Windows + I ).
- Scroll down and select Windows Update.
- Perform any available updates.
- Select Advanced options.
- Under Additional options, click on Optional updates.
- Run any driver updates.
If you’re suddenly encountering the Python permission denied error and none of the above solutions worked, then check for any Windows 11 updates and perform any available driver updates.
If this method didn’t work either, we recommend you use specialized driver update software, Outbyte Driver Updater.
Outbyte Driver Updater is a fast and automated solution for finding all outdated drivers and updating them to their latest versions. The installation process it’s fast and safe so no additional issues will occur.
Outbyte Driver Updater
What is the latest version of Python?
As of the release of this article, the latest version of Python is 3.10.7 which is available for Windows 8 and newer and is not compatible with older versions including Windows 7. Python supports Windows, macOS, Linux/UNIX, and more.
However, If users want to use older versions of Python, they can access releases 2.7 and newer or they can download a specific version of a release.
If you want a quick way to open PY files on Windows 10 and 11, we offer a guide for that as well.
Hopefully, one of the above solutions helped you fix the Python permission denied error in Windows 11. Let us know in the comments which step worked for you or if you have any suggestions for a different solution.
Still experiencing issues?
If the above suggestions have not solved your problem, your computer may experience more severe Windows troubles. We suggest choosing an all-in-one solution like Fortect to fix problems efficiently. After installation, just click the View&Fix button and then press Start Repair.