Errno 13 permission denied python ошибка

Ошибка 13: Отказано в доступе в Python — это ошибка ввода-вывода, которая возникает, когда система не может связаться с вашим кодом для выполнения желаемой операции. Причины включают попытку доступа к несуществующему файлу, уже открытому файлу, открытие каталога в виде файла или наличие неправильных разрешений. Есть несколько способов исправить эту ошибку, например, закрыть другие экземпляры файла, обновить разрешения, убедиться, что вы не обращаетесь к каталогу, и использовать блоки try-except для обработки ошибок.

Ошибка очень проста, как показано ниже:

IOError: [Errno 13] Permission denied

Ошибка ввода-вывода — это тип ошибки времени выполнения. Ошибки во время выполнения вызваны неправильными форматами ввода или когда код не может произвести вывод.

Поскольку в коде нет синтаксических ошибок, интерпретатор Python интерпретирует код, компилирует его, но при выполнении не может разобрать отдельные операторы или выполнить их.

Распространенные причины ошибок ввода/вывода (отказ в доступе)

Ввод, вывод ошибки вызываются несколькими причинами. Некоторые из них:

  • Наиболее распространенной причиной ошибки ввода-вывода является отсутствие указанного файла.
  • При попытке read() или open() файл, система не может взаимодействовать с кодом, если файл уже открыт в другом месте.
  • Если вы пытаетесь открыть каталог вместо файла, но пытаетесь открыть его как файл, это вызовет ошибку ввода/вывода.
  • Если в пути к каталогу есть косая черта, это также может вызвать ошибку ввода-вывода.
  • Если у вас нет разрешения на открытие этого конкретного файла или если Python не имеет доступа к определенному каталогу.

Существует очень подробная статья об ошибках ввода-вывода Python на сайте ask python, вы можете ознакомиться с ней здесь!

Эта ошибка может быть исправлена ​​несколькими способами. Они есть:

  • Убедитесь, что вы правильно пишете файл и не используете путь к каталогу.
  • Убедитесь, что разрешения обновлены, прежде чем пытаться получить доступ к файлу.
  • Путь к файлу должен быть указан без ошибок, таких как косая черта.
  • Файл, который мы пытаемся открыть, не должен открываться в другом месте.
  • Использование блока try и exc, чтобы узнать, где возникает ошибка.

Мы рассмотрим все эти методы подробно один за другим.

Исправление 1: закрыть другие экземпляры файла

Когда определенный файл открывается в Microsoft Excel или Microsoft Word, эта ошибка часто появляется. Это происходит потому, что эти приложения не позволяют другим приложениям изменять файл при использовании через них.

Следовательно, убедитесь, что файлы закрыты, прежде чем пытаться получить к ним доступ через код Python, и убедитесь, что на компьютере с Windows никакие офисные приложения Microsoft не используют ваш файл, когда вы пытаетесь открыть () или прочитать () его.

Исправление 2: обновить разрешения и запустить от имени администратора

При попытке запустить скрипт Python убедитесь, что вы запускаете его через командную строку в режиме администратора.

Это не повлияет на ваши существующие разрешения для других приложений, оно переопределит только разрешение Python для этого конкретного скрипта и никакое другое. Убедитесь, что вы установили Python с необходимыми разрешениями PATH.

Когда вы открываете командную строку, выберите «Запуск от имени администратора» на правой панели, как показано ниже на рисунке с красной стрелкой.

Использование командной строки в режиме администратора

Использование командной строки в режиме администратора.

Исправление 3: убедитесь, что вы не обращаетесь к каталогу

В этом случае вы пытаетесь открыть каталог, а не конкретный файл. Эту проблему можно решить, указав абсолютный путь к файлу.

Например, если имя вашего файла «First_program.txt», вы также можете использовать приведенную ниже команду с open().

open ('D:/SHREYA/documents/First_program.txt','w')

Это помогает избежать ошибок при указании имен файлов или путей и даже каталогов.

Исправление 4: используйте блоки Try и Except для обработки ошибок

В этом случае также можно использовать операторы try и exclude. Блоки try и exclude используются для обработки исключений в Python. Код для следующего будет:

try:
   open('Our_file.txt','r')
except IOError:
   print("The file cannot be opened")

У нас есть подробная статья об обработке исключений Python. Нажмите здесь, чтобы прочитать!

Краткое содержание

Ошибку 13: Отказано в доступе в Python можно устранить с помощью различных методов и понимания ее причин. Применяя эти решения, вы можете избежать сбоев в программировании и обеспечить плавный прогресс. Сталкивались ли вы с какими-либо другими творческими решениями или превентивными мерами для устранения ошибок разрешений?

Ссылка на источник

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:\Personal\IJS\Code\program.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\\Docs\python.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.

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

Gulzar's user avatar

Gulzar

23.7k27 gold badges116 silver badges205 bronze badges

asked Apr 5, 2016 at 18:54

Marc Schmitt's user avatar

11

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

23.7k27 gold badges116 silver badges205 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:\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.

Gulzar's user avatar

Gulzar

23.7k27 gold badges116 silver badges205 bronze badges

answered Apr 7, 2016 at 7:29

Mixone's user avatar

MixoneMixone

1,3271 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

5494 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,4671 gold badge14 silver badges17 bronze badges

answered Apr 7, 2016 at 7:41

dione llorera's user avatar

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

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

896 bronze badges

0

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)

Gulzar's user avatar

Gulzar

23.7k27 gold badges116 silver badges205 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,0634 gold badges21 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

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 May 25 at 15:37

Mobasshir Bhuiya'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

Red's user avatar

RedRed

26.9k7 gold badges36 silver badges58 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:\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.

answered Apr 21, 2021 at 9:54

Noone's user avatar

NooneNoone

1611 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

761 silver badge5 bronze badges

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

3901 gold badge6 silver badges16 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

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

23.7k27 gold badges116 silver badges205 bronze badges

answered Dec 11, 2020 at 15:03

Bendemann's user avatar

BendemannBendemann

73511 silver badges31 bronze badges

2

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"\Desktop\DEV\python\text_files\output.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.

Error 13: Permission Denied in Python is an I/O error that occurs when the system cannot communicate with your code to carry out the desired operation. Causes include trying to access a nonexistent file, an already-opened file, opening a directory as a file, or having incorrect permissions. There are multiple ways to fix this error, such as closing other instances of the file, updating permissions, ensuring you’re not accessing a directory, and using try-except blocks for error handling.

The error is very simple as shown below:

IOError: [Errno 13] Permission denied

An input/output error is a type of runtime error. Runtime errors are caused by wrong formats of input or when the code is unable to produce an output.

Since there are no syntax errors in the code, the Python interpreter interprets the code, compiles it, but when executing, it cannot parse particular statements or execute them.

Common Causes of I/O Errors (Permission Denied)

Input/output errors are caused by several reasons. Some of them are:

  • The most common cause of an I/O error is if the file specified doesn’t exist.
  • When trying to read() or open() a file, the system cannot communicate with the code if the file is already opened somewhere else.
  • If you’re trying to open a directory instead of a file, but trying to open it like a file, it will raise an input/output error.
  • If there is a forward slash in the path of the directory, it might also raise an i/o error.
  • If you don’t have permission to open that particular file or if Python doesn’t have access to the specific directory.

There is a very thorough article on Python i/o errors on ask python, you can check it out here!

There can be more than one way by which this error can be fixed. They are:

  • Making sure you spell the file correctly and not using the path of a directory.
  • Making sure that the permissions are updated before trying to access the file.
  • The path of the file must be specified without any errors such as a forward slash.
  • The file that we’re trying to open shouldn’t be opened somewhere else.
  • Using a try and except block to find out where the error arises.

We’ll look at all these methods in depth one by one.

Fix 1: Close Other Instances of the File

When a particular file is opened in Microsoft excel or Microsoft word, this error frequently pops up. This happens because these applications do not let any other application modify a file when used via them.

Hence, make sure you have the files closed before trying to access them via your python code and make sure that on a windows computer no Microsoft office applications are using your file when you’re trying to open() or read() it.

Fix 2: Update Permissions and Run as Administrator

When trying to run your python script make sure you run it via the command prompt in the administrator mode.

This won’t affect your existing permissions for other applications, it will only override the Python permission for this particular script and no other. Make sure you’ve installed Python with the required PATH permissions.

When you open the command prompt, choose “run as administrator” from the right-hand panel as shown below in the picture with the red arrow.

Using Command Prompt In The Administrator Mode

Using Command Prompt In The Administrator Mode.

Fix 3: Ensure You Are Not Accessing a Directory

In this case, you’re trying to open a directory instead of trying to open a particular file. This problem can be fixed by specifying the absolute path of a file.

For example, if your file name is “First_program.txt” then you might as well use the command below with open().

open ('D:/SHREYA/documents/First_program.txt','w')

This helps in avoiding mistakes in specifying file names or paths and even directories.

Fix 4: Use Try and Except Blocks for Error Handling

The try and except statements can be used as well in this case. Try and except blocks are used to handle exceptions in Python. The code for the following would be:

try:
   open('Our_file.txt','r')
except IOError:
   print("The file cannot be opened")

We have an in-depth article about python exception handling. Click here to read!

Summary

Error 13: Permission Denied in Python can be addressed through various methods and understanding its causes. By applying these solutions, you can avoid hiccups in your programming journey and ensure smooth progress. Have you come across any other creative solutions or preventative measures to tackle permission errors?

Понравилась статья? Поделить с друзьями:
  • Errno 103 anydesk ошибка
  • Errcur2000 ошибка альфа банк что это
  • Err8 стиральная машина haier ошибка
  • Err62 ошибка уаз
  • Err4 carrier ошибка