Errno 13 permission denied как исправить

I’m getting this error :

Exception in Tkinter callback
Traceback (most recent call last):
File "C:Python34libtkinter__init__.py", line 1538, in __call__
return self.func(*args)
File "C:/Users/Marc/Documents/Programmation/Python/Llamachat/Llamachat/Llamachat.py", line 32, in download
with open(place_to_save, 'wb') as file:
PermissionError: [Errno 13] Permission denied: '/goodbye.txt'

When running this :

def download():
    # get selected line index
    index = films_list.curselection()[0]
    # get the line's text
    selected_text = films_list.get(index)
    directory = filedialog.askdirectory(parent=root, 
                                        title="Choose where to save your movie")
    place_to_save = directory + '/' + selected_text
    print(directory, selected_text, place_to_save)
    with open(place_to_save, 'wb') as file:
        connect.retrbinary('RETR ' + selected_text, file.write)
    tk.messagebox.showwarning('File downloaded', 
                              'Your movie has been successfully downloaded!' 
                              'nAnd saved where you asked us to save it!!')

Can someone tell me what I am doing wrong?

Specs :
Python 3.4.4 x86
Windows 10 x64

Gulzar's user avatar

Gulzar

22.4k23 gold badges104 silver badges185 bronze badges

asked Apr 5, 2016 at 18:54

Marc Schmitt's user avatar

10

This happens if you are trying to open a file, but your path is a folder.

This can happen easily by mistake.

To defend against that, use:

import os

path = r"my/path/to/file.txt"
assert os.path.isfile(path)
with open(path, "r") as f:
    pass

The assertion will fail if the path is actually of a folder.

answered Jun 7, 2020 at 11:14

Gulzar's user avatar

GulzarGulzar

22.4k23 gold badges104 silver badges185 bronze badges

1

There are basically three main methods of achieving administrator execution privileges on Windows.

  1. Running as admin from cmd.exe
  2. Creating a shortcut to execute the file with elevated privileges
  3. Changing the permissions on the python executable (Not recommended)

A) Running cmd.exe as and admin

Since in Windows there is no sudo command you have to run the terminal (cmd.exe) as an administrator to achieve to level of permissions equivalent to sudo. You can do this two ways:

  1. Manually

    • Find cmd.exe in C:Windowssystem32
    • Right-click on it
    • Select Run as Administrator
    • It will then open the command prompt in the directory C:Windowssystem32
    • Travel to your project directory
    • Run your program
  2. Via key shortcuts

    • Press the windows key (between alt and ctrl usually) + X.
    • A small pop-up list containing various administrator tasks will appear.
    • Select Command Prompt (Admin)
    • Travel to your project directory
    • Run your program

By doing that you are running as Admin so this problem should not persist

B) Creating shortcut with elevated privileges

  1. Create a shortcut for python.exe
  2. Righ-click the shortcut and select Properties
  3. Change the shortcut target into something like "C:path_topython.exe" C:path_toyour_script.py"
  4. Click «advanced» in the property panel of the shortcut, and click the option «run as administrator»

Answer contributed by delphifirst in this question

C) Changing the permissions on the python executable (Not recommended)

This is a possibility but I highly discourage you from doing so.

It just involves finding the python executable and setting it to run as administrator every time. Can and probably will cause problems with things like file creation (they will be admin only) or possibly modules that require NOT being an admin to run.

Gulzar's user avatar

Gulzar

22.4k23 gold badges104 silver badges185 bronze badges

answered Apr 7, 2016 at 7:29

Mixone's user avatar

MixoneMixone

1,3181 gold badge13 silver badges24 bronze badges

5

Make sure the file you are trying to write is closed first.

answered Feb 7, 2019 at 3:39

Chrono Hax's user avatar

Chrono HaxChrono Hax

5094 silver badges3 bronze badges

0

Change the permissions of the directory you want to save to so that all users have read and write permissions.

Alexander's user avatar

Alexander

2,4571 gold badge14 silver badges17 bronze badges

answered Apr 7, 2016 at 7:41

dione llorera's user avatar

0

You can run CMD as Administrator and change the permission of the directory using cacls.exe. For example:

cacls.exe c: /t /e /g everyone:F # means everyone can totally control the C: disc

answered Mar 10, 2020 at 3:41

Outro's user avatar

OutroOutro

916 bronze badges

0

In my case the problem was that I hid the file (The file had hidden atribute):
How to deal with the problem in python:

Edit: highlight the unsafe methods, thank you d33tah

# Use the method nr 1, nr 2 is vulnerable

# 1
# and just to let you know there is also this way
# so you don't need to import os
import subprocess
subprocess.check_call(["attrib", "-H", _path])


# Below one is unsafe meaning that if you don't control the filePath variable
# there is a possibility to make it so that a malicious code would be executed

import os

# This is how to hide the file
os.system(f"attrib +h {filePath}")
file_ = open(filePath, "wb")
>>> PermissionError <<<


# and this is how to show it again making the file writable again:
os.system(f"attrib -h {filePath}")
file_ = open(filePath, "wb")
# This works

answered Jul 22, 2020 at 21:19

Kacper Kwaśny's user avatar

1

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

answered Dec 17, 2019 at 21:02

codefreak-123's user avatar

The problem could be in the path of the file you want to open. Try and print the path and see if it is fine
I had a similar problem

def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
    filenm=filenm.split("?")[0]
    filenm=("{}.html").format(filenm)
    print("Converted a  file into html that was not compatible")

if ".aspx" in htm:
    htm=htm.replace(".aspx",".aspx.html")
    print("[process]...conversion fron aspx")
if ".jsp" in htm:
    htm=htm.replace(".jsp",".jsp.html")
    print("[process]..conversion from jsp")
if ".php" in htm:
    htm=htm.replace(".php",".php.html")
    print("[process]..conversion from php")

output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))

but after adding this code:

nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
    filenm=("{}index.html").format(filenm)

It Worked perfectly

Gulzar's user avatar

Gulzar

22.4k23 gold badges104 silver badges185 bronze badges

answered Feb 26, 2019 at 11:41

oyamo's user avatar

oyamooyamo

411 silver badge3 bronze badges

in my case. i just make the .idlerc directory hidden.
so, all i had do is to that directory and make recent-files.lst unhidden after that, the problem was solved

henriquehbr's user avatar

henriquehbr

1,0444 gold badges19 silver badges41 bronze badges

answered Dec 14, 2019 at 10:37

Mehrad Mazaheri's user avatar

0

I got this error as I was running a program to write to a file I had opened. After I closed the file and reran the program, the program ran without errors and worked as expected.

answered Sep 6, 2021 at 5:07

Valerie Ogonor's user avatar

1

I faced a similar problem. I am using Anaconda on windows and I resolved it as follows:
1) search for «Anaconda prompt» from the start menu
2) Right click and select «Run as administrator»
3) The follow the installation steps…

This takes care of the permission issues

answered Sep 6, 2018 at 14:38

Chinnappa Reddy's user avatar

0

Here is how I encountered the error:

import os

path = input("Input file path: ")

name, ext = os.path.basename(path).rsplit('.', 1)
dire = os.path.dirname(path)

with open(f"{dire}\{name} temp.{ext}", 'wb') as file:
    pass

It works great if the user inputs a file path with more than one element, like

C:\Users\Name\Desktop\Folder

But I thought that it would work with an input like

file.txt

as long as file.txt is in the same directory of the python file. But nope, it gave me that error, and I realized that the correct input should’ve been

.\file.txt

answered Dec 18, 2020 at 21:40

Ann Zen's user avatar

Ann ZenAnn Zen

26.6k7 gold badges36 silver badges57 bronze badges

2

As @gulzar said, I had the problem to write a file 'abc.txt' in my python script which was located in Z:projecttest.py:

with open('abc.txt', 'w') as file:
    file.write("TEST123")

Every time I ran a script in fact it wanted to create a file in my C drive instead Z!
So I only specified full path with filename in:

with open('Z:\project\abc.txt', 'w') as file: ...

and it worked fine. I didn’t have to add any permission nor change anything in windows.

answered Apr 21, 2021 at 9:54

Noone's user avatar

NooneNoone

1511 silver badge6 bronze badges

That’s a tricky one, because the error message lures you away from where the problem is.

When you see "__init__.py" of an imported module at the root of an permission error, you have a naming conflict. I bed a bottle of Rum, that there is "from tkinter import *" at the top of the file. Inside of TKinter, there is the name of a variable, a class or a function which is already in use anywhere else in the script.

Other symptoms would be:

  1. The error is prompted immediately after the script is run.
  2. The script might have worked well in previous Python versions.
  3. User Mixon’s long epos about administrator execution privileges has no impact at all. There would be no access errors to the files mentioned in the code from the console or other pieces of software.

Solution:
Change the import line to «import tkinter» and add the namespace to tkinter methods in the code.

answered Aug 8, 2021 at 2:30

Helen's user avatar

HelenHelen

861 silver badge5 bronze badges

Two easy steps to follow:

  1. Close the document which is used in your script if it’s open in your PC
  2. Run Spyder from the Windows menu as «Run as administrator»

Error resolved.

answered Feb 11 at 7:33

Ankit Vyas's user avatar

In my case, I had the file (to be read or accessed through python code) opened and unsaved.

PermissionError: [Errno 13] Permission denied: 'path_to_the_open_file'

I had to save and close the file to read/access, especially using pandas read (pd.read_excel, pd.read_csv etc.) or the command with open():

answered Mar 15 at 12:00

Bhanu Chander's user avatar

Bhanu ChanderBhanu Chander

3701 gold badge5 silver badges16 bronze badges

The most common reason for this could be, permission to the folder/file for that particular user.

Grant write permissions to the directory where you want to write files. You can do this by changing the ownership or permissions of the directory using the chmod or chown commands.

Example:

# Change ownership of the directory to the current user
sudo chown -R $USER:$USER /path/to/directory

# Grant write permissions to the directory
sudo chmod -R 777 /path/to/directory

answered 19 hours ago

Mobasshir Bhuiya's user avatar

This error actually also comes when using keras.preprocessing.image so for example:

img = keras.preprocessing.image.load_img(folder_path, target_size=image_size)

will throw the permission error. Strangely enough though, the problem is solved if you first import the library: from keras.preprocessing import image and only then use it. Like so:

img = image.load_img(img_path, target_size=(180,180))

Gulzar's user avatar

Gulzar

22.4k23 gold badges104 silver badges185 bronze badges

answered Dec 11, 2020 at 15:03

Bendemann's user avatar

BendemannBendemann

70511 silver badges30 bronze badges

2

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

Try these solutions to fix PermissionError [Errno 13] Permission denied

by 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… read more


Updated on February 9, 2023

Reviewed by
Vlad Turiceanu

Vlad Turiceanu

Passionate about technology, Windows, and everything that has a power button, he spent most of his time developing new skills and learning more about the tech world. Coming… read more

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

XINSTALL BY CLICKING THE DOWNLOAD FILE

Fix Windows 11 OS errors with Fortect:
This tool repairs common computer errors by replacing the problematic system files with the initial working versions. It also keeps you away from system errors, BSoDs, and repairs damages made by malware and viruses. Fix PC issues and remove viruses damage now in 3 easy steps:

  1. Download and Install Fortect on your PC
  2. Launch the tool and Start scanning to find broken files that are causing the problems
  3. 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.

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. Open security tab.
  4. Select Edit and go through and check permissions. edit permissions to fix permission denied error.
  5. 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

  • File System Error (-2147219200): How to Quickly Fix It
  • Using Microsoft Project templates? We’ve got some good news
  • Microsoft Mesh for Teams: what is it & how to use it
  • Fix: 0x000003eb Windows Installation Driver Error

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.

If this method didn’t work either, we recommend you use specialized driver update software, DriverFix.

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

DriverFix

Fast and simple tool to maintain all drivers updated.

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.

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.

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?

SPONSORED

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.

newsletter icon

Newsletter

The PermissionError: [Errno 13] permission denied to open, read, or write files will be encountered when we provide a folder path instead of a file path when reading a file or when Python does not have the required permissions to perform file operations (open, read, or write).

PermissionError: [Errno 13] Permission denied error is discussed in this article, along with examples of how to resolve this error.

Let us write an example code that would throw the above error message and then we will see how we can fix that error quickly.

1. Insufficient Privilege Issues

Consider a scenario in which you have a local CSV file containing confidential or sensitive data that must be kept secure. If you want to make a file only accessible to you, you can change the file permissions. In order to read the file, we’ll write a Python program that will print its contents.

# Program to Read A file
# Make Sure that Python is not running
# In Admin or Root Mode.
demoFile = open("demoFile.txt", "r")

getContentOfFile = demoFile.read()

print(getContentOfFile)

demoFile.close()

Output:

Traceback (most recent call last):
  File "C:/Coduber/demoFile.txt", line 4, in <module>
    demoFile = open("demoFile.txt", "r")
PermissionError: [Errno 13] Permission denied: 'demoFile.txt'

When we run the code, we receive the following error: PermissionError: [Error code 13] Because the file is created by the root user, a permission denied error occurs. In this case, we are not running the script in elevated mode (admin/root).

If you are using Windows, you can resolve this issue by opening the command prompt in administrator mode and running the Python script to resolve the issue.

In the case of Linux, we can work around the problem by using the sudo command to run the script as the root user. Running the following command will also allow you to determine whether a file’s permissions have been granted.

ls -la

In the preceding example, the file is owned by the root user, and we are not running Python as the root user, so Python is unable to read the file.

We can resolve the problem by modifying the permissions for a specific user or for all users at the same time. The following command will make the file readable and executable to anyone who has access to it.

chmod 755 demoFile.txt

In addition, we can restrict access to specific users rather than making it available to the general public. This can be accomplished by executing the following command.

chown yourUserName:admin demoFile.txt

The following output will be produced when our code is rerun after the appropriate permissions have been granted:

This is Test File.

2. Providing Folder Path Instead Of File Path

As shown in the following example, we provided a folder path rather than a valid file path, resulting in the Python interpreter returning an Errno 13 permission denied error.

# Program to Read A file
# Make Sure that Python is not running
# In Admin or Root Mode.
demoFile = open("C:\Users\Coduber\", "r")

getContentOfFile = demoFile.read()

print(getContentOfFile)

demoFile.close()

Output:

Traceback (most recent call last):
  File "c:UsersCodubertest.py", line 4, in <module>
    demoFile = open("C:\Users\Coduber", "r")
PermissionError: [Errno 13] Permission denied: 'C:\Users\Coduber'

It is possible to resolve the error by providing a valid file path; however, if we accept the file path dynamically, we must change our code in order to verify that the given file path is a valid file before processing it.

# Program to Read A file
# Make Sure that Python is not running
# In Admin or Root Mode.
demoFile = open("C:\Users\Coduber\demoFile.txt", "r")

getContentOfFile = demoFile.read()

print(getContentOfFile)

demoFile.close()

Output:

This is Test File.
Python PermissionError: [Errno 13] Permission denied Fix

3. File Is Already Open By Other Program

If we forget to close the file after performing file operations in Python, it will remain open indefinitely. As a result, we will receive a permission denied error the next time we attempt to access the file because it is already in use by another process and we did not close the file.

Ensure that a file is closed after an i/o operation is performed on it in order to avoid this error from occurring again. For more information on how to read files in Python and how to write files in Python, please see the following articles.

Wrap Up

You will receive the PermissionError: [Errno 13] Permission denied error in Python if you attempt to read a file from a folder path rather than a file path or if the Python does not have the required permissions to perform file operations (open, read, and write).

It is possible to resolve this error by ensuring that the file has been given appropriate permissions by using the chown or chmod commands, as well as by ensuring that Python is running in elevated mode.

Please let me know in the comments if you are still experiencing this problem or if you have a better solution than the one discussed above. I’ll gladly include it here.

Further Read:

  1. Python ValueError: could not convert string to float [Fix]
  2. Python pip: command not found Quick Fix
  3. Python Write Text File
  4. [Fixed] Python TypeError: ‘NoneType’ Object Is Not Subscriptable
  5. [Fixed] Python TypeError: ‘list’ object is not callable

Понравилась статья? Поделить с друзьями:
  • Как в вайбере найти сообщения одного человека
  • Как найти силу тока в момент времени
  • Как найти таблицу в оракл
  • Микрогнатия как исправить
  • Как найти других блогеров