Errno 13 permission denied python windows

Errno 13 Permission denied Python

In python, I am currently experimenting with what I can do with open command. I tried to open a file, and got an error message. Here’s my code:

My error message was:

I looked on the website to try and find some answers and I saw a post where somebody mentioned chmod . 1. I’m not sure what this is and 2. I don’t know how to use it, and thats why I’ve come here.

6 Answers 6

Your user don’t have the right permissions to read the file, since you used open() without specifying a mode.

Since you’re using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.

Check at the location where you try to open the file, if you have a folder with exactly the same name as the file you try to open (the file extension is part of the file name).

The problem here is your user doesn’t have proper rights/permissions to open the file this means that you’d need to grant some administrative privileges to your python ide before you run that command.

As you are a windows user you just need to right click on python ide => select option ‘Run as Administrator’ and then run your command.

And if you are using the command line to run the codes, do the same open the command prompt with admin rights. Hope it helps

If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates. I hope someone will help this info.

Sorry for «bumping» this, but I found that when you specify a file when it is asking for a directory, this happens.

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Как открыть windows run

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

PermissionError: [Errno 13] in python

Just starting to learn some python and I’m having an issue as stated below:

Seems to be a file permission error, if any one can shine some light it would be greatly appreciated.

NOTE: not sure how Python and Windows files work but I’m logged in to Windows as Admin and the folder has admin permissions.

I have tried changing .exe properties to run as Admin.

4 Answers 4

. you’re trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

should work well if you just have the permission on a.txt . You may want to use a raw ( r -prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

For me, I was writing to a file that is opened in Excel.

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

For me, I got this error when I was trying to write a file to a folder and wanted to make sure the folder existed. I accidentally used:

but the second line means «make a directory at this exact path (and make its parents too, without throwing errors for them existing already)». The third line then throws a PermissionError , because you can’t use open() on a directory path, of course! The second line should have been:

Not the answer you’re looking for? Browse other questions tagged python python-3.x or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

PermissionError: [Errno 13] Permission denied

I’m getting this error :

When running this :

Can someone tell me what I am doing wrong ? Thanks

Specs : Python 3.4.4 x86 Windows 10 x64

13 Answers 13

I am seeing a bit of activity on my answer so I decided to improve it a bit for those with this issue still

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)

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

  • 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
Читайте также:  Monitor setting windows 10

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

2) 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

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

Ошибка:[Errno 13] Permission denied

Разработать программу о телефонной компании, которая хранит данные о
своих клиентах. Для простого учета использовать класс Customer (Клиент),
который содержащий атрибуты:
— поле name: имя клиента (чтение/запись);
— свойство balance: баланс счета клиента (только чтение);
— метод record_payment(): выполняет пополнение баланса;
— метод record_call(): выполняет обработку звонка клиента в зависимости
от:типа звонка: «городской» (5 руб./мин.) и «мобильный» (1 руб./мин.);
— количества минут разговора.
Повременный: «городской» (5 руб./мин.) и «мобильный» (1 руб./мин.);
После 10 минут в 2 раза дешевле: после 10 минут звонка на городской
номер каждая вторая минута бесплатно; в остальном как Повременный;
Плати до 5 минут: до 5 минут разговора в 2 раза дешевле тарифа
Повременный, после — в 2 раза дороже.

Возникло исключение: PermissionError [Errno 13] Permission denied:
Выскакивает ошибка Возникло исключение: PermissionError Permission denied: ‘Results’ File.

Запись в файл: Permission denied
По мере выполнения скрипта надо записывать кое какие данные в текстовой файл. def.

Открытие файла, ошибка [Errno 2] No such file or directory
Помогите, пожалуйста. Не могу разобраться в работе с файлами. Открытие файла, как я понимаю: f =.

IOError: [Errno 13] Permission denied when trying to open hidden file in “w” mode

I want to replace the contents of a hidden file, so I attempted to open it in w mode so it would be erased/truncated:

But this resulted in a traceback:

However, I was able to achieve the intended result with r+ mode:

Q. What is the difference between the w and r+ modes, such that one has «permission denied» but the other works fine?

UPDATE: I am on win7 x64 using Python 2.6.6, and the target file has its hidden attribute set. When I tried turning off the hidden attribute, w mode succeeds. But when I turn it back on, it fails again.

Q. Why does w mode fail on hidden files? Is this known behaviour?

3 Answers 3

It’s just how the Win32 API works. Under the hood, Python’s open function is calling the CreateFile function, and if that fails, it translates the Windows error code into a Python IOError .

The r+ open mode corresponds to a dwAccessMode of GENERIC_READ|GENERIC_WRITE and a dwCreationDisposition of OPEN_EXISTING . The w open mode corresponds to a dwAccessMode of GENERIC_WRITE and a dwCreationDisposition of CREATE_ALWAYS .

Читайте также:  Include linux config h

If you carefully read the remarks in the CreateFile documentation, it says this:

If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute. To avoid the error, specify the same attributes as the existing file.

So if you were calling CreateFile directly from C code, the solution would be to add in FILE_ATTRIBUTE_HIDDEN to the dwFlagsAndAttributes parameter (instead of just FILE_ATTRIBUTE_NORMAL ). However, since there’s no option in the Python API to tell it to pass in that flag, you’ll just have to work around it by either using a different open mode or making the file non-hidden.

Here are the detailed differences:-

«r» Open text file for reading. The stream is positioned at the beginning of the file.

«r+» Open for reading and writing. The stream is positioned at the beginning of the file.

«w» Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

«w+» Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

«a» Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

«a+» Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

On Windows, ‘b’ appended to the mode opens the file in binary mode, so there are also modes like ‘rb’, ‘wb’, and ‘r+b’. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a ‘b’ to the mode, so you can use it platform-independently for all binary files.

So if you are using w mode, you are actually trying to create a file and you may not have the permissions to do it. r+ is the appropriate choice.

If you are in a situation where you do not yet know where your .picasi.ini exists or not and your windows user has file creation permissions in that directory and you want to append new information instead of starting at the beginning of the file (a.k.a «append»), then a+ will be the appropriate choice.

It has nothing to do with whether your file is hidden or not.

Оцените статью