PermissionError: [Errno 13] Permission denied
Asked Answered
P

19

114

I'm getting this error :

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__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

Psf answered 5/4, 2016 at 18:54 Comment(11)
shouldn't place_to_save be simply goodbye.txt? I'm not sure how Windows would behave, but on Linux you'll be writing to root dir (/), and that's always a bad idea. Instead of manual string manipulation you should use os.path.join(directory, selected_text).Northernmost
try open(place_to_save, 'w+') instead of open(place_to_save, 'wb'). I remember seeing some other SO posts about the same issue,Camail
An MCVE stackoverflow.com/help/mcve should be one line: open('/goodbye.txt', 'wb'). If this also raises, then tkinter is irrelevant and should be removed as a tag. This should be tagged with the OS, as that is relevant.Basilisk
does the user have enough rights to open that file? might be locked to admin or something like thatSyncopate
The error is telling you precisely what the problem is: the user doesn't have permission to write to the file. The first step is to do some debugging to make sure that place_to_save is what you think it is.Husbandry
The code is correctly intented. I'm just calling the function "download()" The "place_to_save" is exactly where I think the file must be. That must probably be a permission problem, but how to solve it ?Psf
What is the output of print(directory, selected_text, place_to_save)? My guess is that directory is an empty string for some reason. I would try adding initialdir=r'c:/' to filedialog.askdirectory call.Brittenybrittingham
What J.J. Hakala said. Even better: do print((directory, selected_text, place_to_save)), as that will print a tuple, which will show you the representation of those strings.Egocentric
purely for informative purposes: Why does this question have so many downvotes? If they are downvoting for what I think they are, isn't the appropriate response a flag?Syncopate
@Syncopate I think this is because the code is not minimal. The only relevant line is ` with open(place_to_save, 'wb') as file:`, and maybe the path itself. Also the stack trace is not full.Generate
Really misleading Windows error. Have a look at this github discussion that is addressing the problem github.com/orgs/pyinstaller/discussions/5468Neusatz
G
193

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.

Generate answered 7/6, 2020 at 11:14 Comment(1)
I wish the original asker would accept this as the answer. There are many, many questions about this error, and this is the only answer that really seems to be right. Often this error occurs despite the file having correct permissions set, and so the answer has to be something else. This is it.Meteoritics
S
46

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:\Windows\system32
    • Right-click on it
    • Select Run as Administrator
    • It will then open the command prompt in the directory C:\Windows\system32
    • 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_to\python.exe" C:\path_to\your_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.

Syncopate answered 7/4, 2016 at 7:29 Comment(5)
What if this hapens from PyCharm? I am unable to give admin privilages to python.exe because this is a work computer.Generate
In that case you probably need to contact your IT support team. Or just move the file creation/deletion to a directory you have write access on your work pcSyncopate
Also try running PyCharm as an Admin, if you can, not the python.exeSyncopate
@Syncopate Why does the OP need admin privileges? If he owns the destination folder, and owns the program, then surely the levels match? How does one debug what level you're running at, and what level you need for any specific destination?Gwenni
@Gwenni I beleive it was due to the fact that their code allows the user to CHOOSE a directory to save in also some work and school pcs have a lot of gpo policies blocking write access to some folders that are sometimes shared, he needs the priv if he doesnt own it is the point, you know the level in microsoft due to your userSyncopate
N
46

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

Napalm answered 7/2, 2019 at 3:39 Comment(0)
C
11

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

Cortney answered 7/4, 2016 at 7:41 Comment(0)
P
4

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!

Pavlodar answered 17/12, 2019 at 21:2 Comment(0)
H
4

In my case the problem was that I hid the file (The file had hidden attribute):
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

Ham answered 22/7, 2020 at 21:19 Comment(1)
WARNING: the first two snippets here have a vulnerability called OS command injection: whitehatsec.com/glossary/content/os-command-injection ; always use subprocess and never combine shell=True or os.system and user-controlled variables.Dart
Z
3

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)
Zealand answered 26/2, 2019 at 11:41 Comment(0)
C
3

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
Curlicue answered 10/3, 2020 at 3:41 Comment(0)
D
2

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

Discount answered 14/12, 2019 at 10:37 Comment(0)
L
2

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.

Latchkey answered 6/9, 2021 at 5:7 Comment(1)
Please add further details to expand on your answer, such as working code or documentation citations.Groundspeed
E
2

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

Essen answered 25/5, 2023 at 15:37 Comment(1)
Thank You so much for your insight. I was doing so many different stuffs to solve my problem for last 2 days. It's now solved. Note for Others: please change the $USER:$USER to $ROOT:$ROOT or the 'username' of your OS.Lourielouse
S
0

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

Setback answered 6/9, 2018 at 14:38 Comment(0)
P
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
Pyrrhonism answered 18/12, 2020 at 21:40 Comment(2)
or you could just use path = os.path.abspath(path)Generate
Also, instead of all the "\\", you can (and should) use os.path.sep, or better, use os.path.joinGenerate
M
0

As @gulzar said, I had the problem to write a file 'abc.txt' in my python script which was located in Z:\project\test.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.

Military answered 21/4, 2021 at 9:54 Comment(0)
C
0

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.

Chorizo answered 8/8, 2021 at 2:30 Comment(0)
L
0

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():

Licence answered 15/3, 2023 at 12:0 Comment(0)
L
0

I got the same error in windows environment and python 3.11.4. In my case, the issue is the absolute path of the file is too long.

Leontineleontyne answered 6/11, 2023 at 22:49 Comment(0)
H
-1

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.

Hyalo answered 11/2, 2023 at 7:33 Comment(0)
B
-2

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))
Bendick answered 11/12, 2020 at 15:3 Comment(2)
I was going to edit your namings to be cohesive, then noticed you got the error for folder_path, and didn't get the error for img_path. This makes me believe Keras isn't bugged, and the real solution to your problem is https://mcmap.net/q/188462/-permissionerror-errno-13-permission-deniedGenerate
error is not specific to KerasVentricular

© 2022 - 2024 — McMap. All rights reserved.