Python windows permission denied

Last Updated :
02 Aug, 2024

When your Python code encounters a situation where it lacks the necessary permissions to access a file or directory, it raises PermissionError: [Errno 13] Permission denied in Python. This article will explore how to address the Errno 13 Error in Python effectively.

What is PermissionError: [Errno 13] Permission Denied in Python?

PermissionError: [Errno 13] Permission Denied denotes a situation where a program attempts to execute an operation—such as file reading or writing—without the requisite permissions. This error typically arises when a user lacks the necessary privileges to access, modify, or execute a particular file or directory. The error message associated with Errno 13 explicitly indicates that permission is denied for the specified operation.

Error Syntax

PermissionError: [Errno 13] Permission denied

below, are the reasons for the occurrence of PermissionError: [Errno 13] Permission denied in Python:

  • Improper File Path Handling
  • Incorrect File Content in Python

Improper File Path Handling

This Python code opens a file named «GFG.txt» for writing and writes «Hello, world!» into it. However, the file path contains backslashes (\), which might cause issues if not handled correctly.

Python

with open(r"C:\Users\R.Daswanta kumar\OneDrive\Pictures\GFG\file\GFG.txt", "w") as file:
    file.write("Hello, world!")

Output:

Screenshot-2024-04-03-022752

Incorrect File Content with Python

Below, code to overwrite the content of a file named «GFG.txt» located at a specific path. If executed without sufficient permissions, Python will raise a PermissionError (Error 13) indicating a permission denied error.

Python

file_path = r"C:\Users\R.Daswanta kumar\OneDrive\Pictures\GFG\file\GFG.txt"

with open(file_path, "w") as file:
    new_content = "New content to replace the existing content."
    file.write(new_content)

print("File content modified successfully!")

Output:

ss2

Solution for PermissionError: [Errno 13] Permission Denied in Python

Below, are the approaches to solve PermissionError: [Errno 13] Permission Denied in Python:

  • Proper File Path Handling
  • Correct File Content in Python

Proper File Path Handling

Below, code defines a file path and opens a file named «GFG.txt» in write mode, enabling it to overwrite existing content. It then replaces the content with the specified new text and confirms successful modification.

Python

file_path = r"C:\Users\R.Daswanta kumar\OneDrive\Pictures\GFG\file\GFG.txt"

with open(file_path, "w") as file:
    new_content = "New content to replace the existing content."
    file.write(new_content)

print("File content modified successfully!")

Output

File content modified successfully

Correct File Content in Python

The following code first checks if the file exists, then attempts to modify its permissions to allow writing. If successful, it proceeds to overwrite the file’s content with new text. If the user lacks necessary permissions, it prints a message indicating permission denial. Finally, it confirms both the modification of file permissions and the content.

Python

import os

file_path = r"C:\Users\R.Daswanta kumar\OneDrive\Pictures\GFG\file\GFG.txt"

try:
    if os.path.exists(file_path):

        os.chmod(file_path, 0o666)
        print("File permissions modified successfully!")
    else:
        print("File not found:", file_path)
except PermissionError:
    print("Permission denied: You don't have the necessary permissions to change the permissions of this file.")

with open(file_path, "w") as file:
    new_content = "New content to replace the existing content."
    file.write(new_content)

print("File content modified successfully!")

Output

File content modified successfully

Conclusion

In conclusion , To sum up, Error 13 is a frequent Python issue that arises from inadequate permissions when attempting to access certain files or folders. You may simply fix this problem and create reliable Python code by using the ‘os’ module, comprehending file permissions, and putting appropriate error handling in place.


Readers help support Windows Report. We may get a commission if you buy through our links.

Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more

Python is designed to build 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 various 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 leading 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.

Ensure the file exists and you're using the correct file path to fix python permission denied error.

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.

use chomd 755 to fix python permission denied error in windows 11.

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

  1. Navigate to the location of your file in file explorer.
  2. Right-click on the file and select Properties.
    open file properties.

  3. Click the Security tab then select your name under Group or user names.
  4. Select Edit and go through and check permissions.
  5. Click Apply then OK.

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

  • Recent Windows 11 update lets you disable profanity filter in voice typing
  • Meta under fire after AI chatbot caught having sexual talks with minors
  • OpenAI decides to reverse recent GPT-4o update after user find bot being overly appeasing
  • Microsoft’s hotpatching for Windows Server 2025 to be subscription-based starting July

4. Turn off execution aliases

  1. Click on Start and open Settings (or press Windows + I).
  2. Open Apps then select Apps & features.
    open windows 11 apps and features.

  3. Open the drop-down menu next to More settings.
  4. Click App execution aliases.
    go to app execution aliases.

  5. Locate the two App Installers for python.exe and python3.exe and toggle both to Off.
    Disable python aliases to fix permission denied error in windows 11.

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

  1. Click on Start and open Settings (or press Windows + I).
  2. Scroll down and select Windows Update.
    Open windows update in settings.

  3. Perform any available updates.
  4. Select Advanced options.
    open windows 11 advanced options.

  5. Under Additional options, click on Optional updates.
    Do any optional updates to fix python permission denied error.

  6. 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.

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 10 and newer and is not compatible with older versions, including Windows 7. Python supports Windows, macOS, Linux/UNIX, and more.

Python version 3.10.7.

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. To learn how to deal with errors, be sure to visit our Try-except-print in Python guide.

We also have a great guide on what to do if _xsrf argument missing from post, so don’t miss it. We also have a new guide on Cannot open shared object no such file or directory error, so don’t miss it.

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.


Megan Moore

Megan is a Windows enthusiast and an avid writer. With an interest and fascination in all things tech, she enjoys staying up to date on exciting new developments in the computer and gaming world.

When not falling down a rabbit hole of tech news and information, she enjoys painting, watching movies, and taking her dramatic husky for long walks.


📝 Title: Troubleshooting «Permission Denied» Error While Running Python on Windows 10

Introduction

👋 Hey there! If you’re reading this, you might have encountered a frustrating «Permission Denied» error when trying to run Python on your Windows 10 machine. Don’t worry, we’ve got you covered! In this blog post, we will explore common issues that could be causing this problem and provide easy solutions to get you back on track. Let’s dive in! 🚀

Understanding the Issue

Based on the information you provided, it seems the recent Windows 10 update may have interfered with Python, causing the «Permission Denied» error. This is a common issue experienced by many users. The error can occur when the necessary permissions for Python are not properly set or when certain files/folders cannot be accessed.

Potential Solutions

Here are a few simple solutions you can try to fix the «Permission Denied» error:

Solution 1: Run as Administrator

  1. Right-click on the command prompt or terminal icon.

  2. Choose the «Run as administrator» option.

  3. Try running the Python command again (python --version) and check if the error persists.

Running Python as an administrator can sometimes resolve permission-related issues. Give it a shot and let’s see if it works! 💪

Solution 2: Check Permissions

  1. Locate your Python installation directory (e.g., C:\Python37).

  2. Right-click on the folder and select «Properties.»

  3. Navigate to the «Security» tab.

  4. Check if your user account has the necessary permissions to access the Python folder and its contents. You should have at least «Read & execute» and «Read» permissions.

  5. If your user account is missing these permissions, click «Edit» to modify the permissions.

  6. Add your user account if it’s not listed and grant the necessary permissions.

  7. Click «Apply» and then «OK» to save the changes.

  8. Try running Python again and see if the issue is resolved.

Ensuring that your user account has the appropriate permissions can help resolve the «Permission Denied» error.

Solution 3: Reinstall Python

  1. Uninstall the existing Python installation from your system.

  2. Download the latest version of Python from the official website (https://www.python.org/downloads/).

  3. Run the installer with administrative privileges (right-click on the installer and select «Run as administrator»).

  4. Follow the installation instructions and complete the process.

  5. Try running Python once again and check if the error persists.

A fresh installation of Python could eliminate any discrepancies causing the error.

Conclusion

🎉 Congratulations! You’ve learned some simple yet effective solutions for fixing the «Permission Denied» error while running Python on Windows 10. By following the steps outlined in this guide, you should be able to overcome this frustrating issue.

If you’re still encountering the error or have any other questions, feel free to leave a comment below. Our tech community is always here to help you out! Together, we’ll conquer any technical challenge that comes our way. 💪

Call-to-Action

👍 Do you know someone who’s struggling with the «Permission Denied» error in Python on Windows 10? Share this blog post with them and help them out! Let’s spread the knowledge and make their coding experience smoother. Don’t forget to leave a comment if you found this guide helpful or have any questions. Happy coding! 😊

  • Author
  • Recent Posts

started writing code around 20 years ago, and throughout the years, I have gained a lot of expertise from hands-on experience as well as learning from others. This website has also grown with me and is now something that I am proud of.

Errno 13 permission denied is an error message when Python cannot read your file due to an error in your code or a conflict in the file system of your operating system. This article will show you other causes of this error message as well, and we’ll teach you how to fix them all.

Errno 13 Permission Denied

Everything that you’ll learn will let you understand how Python handles files and how it responds if it encounters a problem in the process. Now, switch on your computer, and let’s solve the “permission denied” error in Python.

JUMP TO TOPIC

  • Why Is Python Denied a Permission? All Possible Causes
    • – You’re Reading a Folder Like a File
    • – Python Is Not Permitted To Read the File
    • – The File Is Opened in Another Program
    • – There Is Forward Slash Before the Folder Name
    • – You’re Using “Python 3.7” From Microsoft Store
  • How To Solve the “Permission Denied Error” in Python? Simplified
    • – Confirm That You’re Opening a File Using “OS.path.isfile()”
    • – Grant Python Permissions To Read the File
    • – Close the Application That’s Using the File
    • – Remove the Forward Slash Before Your Folder
    • – Toggle off Application Execution Aliases in Windows
  • Conclusion

Why Is Python Denied a Permission? All Possible Causes

Python was denied permission because of the following:

  • You’re reading a folder like a file
  • Python is not permitted to read the file
  • The file is opened in another program
  • There is a forward slash before the folder name
  • You’re using “Python 3.7” from Microsoft Store

– You’re Reading a Folder Like a File

The first cause of the “permission denied” error is when Python tries to open a folder name like a file using Python’s in-built “open()” function. By default, this function will open files in a directory, and it will return a file object. But it’s not designed to open a folder, and if you tell it to open a folder, that’s when the permission error occurs.

For example, the following code aims to open a file in a directory, but there is no reference to the file.

# An attempt to open a folder name

# results in a permission error.

file = open(“C:\\Users\\HP\\Desktop\\PIE\\PIE_CLE_01”)

# Read the file.

file_content = file.read()

# Print the file.

print(file_content)

# Close the file handle.

file.close()

– Python Is Not Permitted To Read the File

When Python is not permitted to read a file, it will also report a “permission denied” error. This happens because, on operating systems like Windows and Linux, you can configure file access for a user account.

So, if your user account does not have access to a file, any Python installation for your account cannot open the file. This means any attempt to open the file using the “open()” function in Python will result in a permission error.

– The File Is Opened in Another Program

In the Windows operating system, if a file is opened in an application, you can’t read it using Python. For example, if you’re working with “File_A.csv” in Microsoft Excel, Windows will not allow Python to open “File_A.csv” using its “open()” function.

This prevents conflicts where one application can make changes, and another can delete those changes at the same time. That’s because, when you open a file using the “open()”, you can change the file content.

Errno 13 Permission Denied Causes

– There Is Forward Slash Before the Folder Name

In Unix, if there is a forward slash before the folder name in your file-uploading code, you’ll run into the permission error. That’s because the forward slash before a folder’s name in Unix is a sign that the folder should be in the “root directory”.

This directory contains the core and sensitive files and directories of your Unix system, for example, “/bin/” and “/usr/”. However, ordinary processes like your file-uploading code don’t have permission to modify this “root directory”.

– You’re Using “Python 3.7” From Microsoft Store

If you’re using “Python 3.7” from Microsoft Store, you can encounter the “permission denied” error while working with Python. That’s because this Python has two executables, “python.exe” and “python3.exe” and this can create a conflict when working with files.

How To Solve the “Permission Denied Error” in Python? Simplified

You can solve the “permission denied error” in Python using the following:

  • Confirm that you’re opening a file using “os.path.isfile()”
  • Grant Python permissions to read the file
  • Close the application that’s using the file
  • Remove the forward slash before your folder
  • Toggle off application execution aliases in Windows



– Confirm That You’re Opening a File Using “OS.path.isfile()”

Before your code opens a file, you should confirm that the “file” is a file using “os.path.isfile()”. The “isfile()” function accepts a “file path”, and it will return Boolean “true” if the path belongs to a file and “false” otherwise.

Now, the following is the updated code that was reading a folder name instead of a file. This time, we use “os.path.isfile()” to check the file path, and if it’s a file, you can read and print the file content.

import os

# Assign a file path

file_path = “C:\\Users\\HP\\Desktop\\PIE\\PIE_CLE_01”

# Check the file

is_file = os.path.isfile(file_path)

# If it’s a file, open and print the file

# content.

if (is_file):

file = open(file_path)

# Read the file

file_content = file.read()

# Print the file

print(file_content)

# Close the file handle

file.close()

else:

print(“Not a file.”)

– Grant Python Permissions To Read the File

If you have “File_A.txt” that’s not accessible to your user account and your Python file (“File_B.py”), you can change the file permissions of “File_A.txt” or update the “file permissions” of the Python file, “File_B.py”.

On Windows, you can use the following steps to update the privilege of your Python file:

  1. Open Windows explorer and navigate to the location of the Python file.
  2. Right-click on it and select “Properties” to open a dialog window
  3. Select the “Security” tab and choose your account username under “Group or user names”.
  4. Click on “Edit” and set the permissions that are required. This will be “Full Control”, “Modify”, “Read & execute”, “Read” and “Write”.
  5. Save your changes using the “Apply” button and click on “OK” to confirm.

On Linux, you can change the file permission using the “chmod 755 your_file_name.extension” or “chown account_username:admin your_file_name.extension”.

The “chmod 755” command will give you read/write/execute privilege on “your_file_name.extension” and the latter is a valid file on your computer. While the “chown” command is short for “change ownership” and here, the command will assign you administrator rights on the file.

You can use command on your Linux terminal, and then you can read the file using Python and the “open()” function.

– Close the Application That’s Using the File

When another application has opened a file that you’ll like to read in Python, you should close the application. On Windows, you do the following:

Errno 13 Permission Denied Fixes

  1. Locate the application’s icon on the Taskbar.
  2. Right-click on it and select “Close”.

However, if the application failed to close using the steps above, you can use the command prompt:

  1. Click on the “Start” menu and search for “cmd”.
  2. Right-click the command prompt and select “Run as administrator”.
  3. Type “tasklist” on the command line and hit “enter” on your keyboard.
  4. Locate the application from the command output and take note of its PID number.
  5. Type the following and replace 1234 with the application’s PID: taskkill /f /PID 1234
  6. Press enter on your keyboard to close the application.
  7. Return to your Python code, and it should have access to the file.

– Remove the Forward Slash Before Your Folder

While working on Unix, you should remove the forward slash from your folder name to prevent the permission error. So, in your code, if you have something like “path = ‘/folderX/folderY’” change it to “path = ‘folder1/folder2′”.

From the latter, we removed the forward-slash (“/”) before “folder1”, and this defaults it to the current working directory. This is safe, and Unix will not stop your code from uploading to “folder1”.

– Toggle off Application Execution Aliases in Windows

You can toggle off application execution aliases in Windows if you’re getting the permission “denied error” from the Python that’s installed from Microsoft Store. To do this, use the following steps:

  1. Click on the “Start” menu and select “Settings”.
  2. Locate “Apps” in the left sidebar and choose “Apps & features”.
  3. Open “More settings” and click on “App execution aliases”.
  4. Locate the application installers for “python3.exe” and “python.exe” and toggle them off.
  5. Switch back to your Python code, and it should read your file.

Conclusion

This article explains why Python shows the “errno 13 permission denied” error and how you can fix it. The following are what you should remember about this error:

  • An attempt to read a folder name like a file will result in the permission denied error.
  • You will get a permission error if your user account is not permitted to read a file.
  • If an application like Microsoft Excel has the file opened, an attempt to read the file in Python will result in a permission error.
  • You can solve the “permission denied” error by checking the validity of the file using “os.path.isfile()” or “chmod 755 your_file_name.extension”.

At this stage, you know how to solve and prevent the “Python permission” error. Teach your fellow Python developers your newly found knowledge by sharing our article.

  1. What Is the IOError: [Errno 13] Permission denied in File Handling in Python

  2. How to Fix the IOError: [Errno 13] Permission denied in Python

  3. How to Use the chmod Command to Change the Permissions of a File in Python

How to Fix IOError: [Errno 13] Permission Denied in Python

It is common to get IOError because we humans mostly interact with the GUI of a computer; we understand the difference between folders, files, compressed files or applications from the visuals.

We have interacted with folders, files, compressed files or applications so often that now our brains sometimes do not process to differentiate among these.

But on the other hand, you have to feed everything to computers they do not understand the visuals only; rather, you have to provide the complete details.

What Is the IOError: [Errno 13] Permission denied in File Handling in Python

In file handling, you need to provide the complete path of the file you want to access; otherwise, you will get the IOError. If you want to open a file but have provided the path of the folder instead, you will face the IOError: [Errno 13] Permission denied.

Below is a code example of the error in Python.

# opening file
f = open("E:\Projects\Test_folder", "r")

Output:

PermissionError: [Errno 13] Permission denied: 'E:\\Projects\\Test_folder'

In the above example, we are trying to open the Test_folder in reading mode, but this has thrown the PermissionError: [Errno 13] Permission denied.

How to Fix the IOError: [Errno 13] Permission denied in Python

To fix this, you need to enter the right path to the file you want to access, not the folder. Let’s say we have two files in the Test_folder.

import os

# Folder Path
folder_path = "E:\Client Project Report\Test_folder"

# display all files in a folder
print(f"All files in the Test_folder are\n{os.listdir(folder_path)}")

# file path
file_path = "E:\Client Project Report\Test_folder\Test_file_1.txt"

# read file
f = open(file_path, "r")
print(f"\n{f.read()}")

# file closed
f.close()

Output:

All files in the Test_folder are
['Test_file_1.txt', 'Test_file_2.txt']

Hi There!
This is test file 1

After providing the path of the file, the error is resolved. Also, it is a good practice to close the opened files in Python so no one can further read and write that file until and unless it is opened again, and if you are trying to write or read a closed file, it will raise a ValueError.

Although Python automatically closes a file when the reference object of the file is assigned to another file. But still, it is a good practice to close a file with the close() function.

In addition, you can also use the exception handling mechanism like try-catch blocks to catch such errors and keep your program safe from crashing.

How to Use the chmod Command to Change the Permissions of a File in Python

As discussed, the IOError: [Errno 13] Permission denied occurs when you try to open a file that is not permitted.

Let’s say you want to open a folder that is not allowed to your access, but still, you try to write a script in Python to open that folder, the permission to access the folder will be denied, and the Python compiler will throw the error.

To resolve this error, we can use the chmod command, which stands for change mode. The chmod() requires two arguments, the path of the file/folder you want to access and the file mode.

The chmod command is used to change the file permission of a file, and it is done by changing the permission flags of a particular file.

The permission flags are represented by a three-digit octal value used to specify read, write, and execute permissions for the file owner, the file group, and all other users.

Syntax of chmod:

The command takes two arguments:

  1. The first is the path to the file whose permissions you want to change.
  2. And the second is the permission you want to set.

Let’s say you want to give read and write permissions to everyone for a file named filename; you would use the following command.

chmod 777 filename

The Python script for the above command would be:

import os

os.chmod("my_file", 0o777)

This piece of code can also be represented as:

import os
import stat

path = "E:\Project\file1.txt"

# stat.S_IRWXU --> All permissions (Read, write, and execute) to the owner
# stat.S_IRWXG --> All permissions (Read, write, and execute) to group
# stat.S_IRWXO --> All permissions (Read, write, and execute) to others

print(os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO))

This would give everyone read, write, and execute permissions of the specific file.

What Does the Three Octal Number Represent in chmod

The permissions of a file can be represented using an octal number. The octal number is made up of three digits, each of which represents different permission.

  1. The first digit represents the owner’s permission.
  2. The second digit represents the group’s permissions.
  3. And the third digit represents the permissions for others.

The permissions of a file can be changed by using the chmod command with the octal number representing the desired permissions.

For example, to give the owner of a file read, write, and execute permissions while giving the group and others read and execute permissions only, the octal number 755 can be used.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Этот компьютер не соответствует минимальным требованиям к системе для работы с windows 11
  • Фильтр смарт скрин как включить windows 10
  • Как узнать пароль администратора в windows 10 не сбрасывая его
  • Восстановление запуска windows 7 как исправить
  • Как называется тачпад в диспетчере устройств windows 10