python – PermissionError: [Errno 13] Permission denied
python – PermissionError: [Errno 13] Permission denied
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 = rmy/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.
There are basically three main methods of achieving administrator execution
privileges on Windows.
- Running as admin from
cmd.exe
- Creating a shortcut to execute the file with elevated privileges
- 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:
-
Manually
- Find
cmd.exe
inC: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
- Find
-
Via key shortcuts
- Press the windows key (between
alt
andctrl
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
- Press the windows key (between
By doing that you are running as Admin so this problem should not persist
B) Creating shortcut with elevated privileges
- Create a shortcut for
python.exe
- Righ-click the shortcut and select
Properties
- Change the shortcut target into something like
C:path_topython.exe C:path_toyour_script.py
- 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.
python – PermissionError: [Errno 13] Permission denied
Make sure the file you are trying to write is closed first.