Permission denied python что делать
Перейти к содержимому

Permission denied python что делать

  • автор:

PermissionError: [Errno 13] Permission denied. Что делать?

По поводу оформления:
Поместите код в блок для исходных кодов. Для этого нажмите кнопку < / > на панели и выберите Python. Оформление вопроса в таком виде, просто издевательство для глаз. В Python важны именно отступы, а у Вас все сливается

Это замечание. Сейчас попытаюсь разобраться в вопросе

Не сработало скорее всего из за того, что «\» это спец. символ. Используется для обозначения таких вещей как конец строки (\n), табуляция (\t). В Вашем случае, скорее всего пыталась понять что значит \д, \G и т.д. Для написания символа \ в строках используют \\.
В зависимости от версии Python может быть проблема и в кодировке пути. Т.к. есть различие русских символов в UTF8 и cp1251 которая используется обычно в Windows.

Fix Python PermissionError: [Errno 13] Permission denied

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:

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.

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:

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:

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.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Search

Type the keyword below and hit enter

Ezoic

report this ad

Click to see all tutorials tagged with:

Ezoic

report this ad

Python PermissionError: [Errno 13] Permission denied

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.

What is PermissionError: [Errno 13] Permission denied error?

We get this error mainly while performing file operations such as read, write, rename files etc.

  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.

Output

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.

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.

We can also give permission to specific users instead of making it readable to everyone. We can do this by running the following command.

When we run our code back after setting the right permissions, you will get the following output.

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.

Output

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.

Output

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.

Ezoic

report this ad

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 .

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:

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.

  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:

  • 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

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *