Permissionerror errno 13 permission denied python windows 10

I'm getting this error : Exception in Tkinter callback Traceback (most recent call last): File "C:Python34libtkinter__init__.py", line 1538, in __call__ return self.func(*args) File &...

I’m getting this error :

Exception in Tkinter callback
Traceback (most recent call last):
File "C:Python34libtkinter__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

20.8k22 gold badges104 silver badges173 bronze badges

asked Apr 5, 2016 at 18:54

Marc Schmitt's user avatar

10

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

20.8k22 gold badges104 silver badges173 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: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
  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_topython.exe" C:path_toyour_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

20.8k22 gold badges104 silver badges173 bronze badges

answered Apr 7, 2016 at 7:29

Mixone's user avatar

MixoneMixone

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

5014 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,4571 gold badge13 silver badges17 bronze badges

answered Apr 7, 2016 at 7:41

dione llorera's user avatar

0

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

916 bronze badges

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

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)

It Worked perfectly

Gulzar's user avatar

Gulzar

20.8k22 gold badges104 silver badges173 bronze badges

answered Feb 26, 2019 at 11:41

oyamo's user avatar

oyamooyamo

311 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,0243 gold badges22 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

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

Ann Zen's user avatar

Ann ZenAnn Zen

26.3k7 gold badges35 silver badges56 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:projecttest.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

1311 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

861 silver badge5 bronze badges

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

20.8k22 gold badges104 silver badges173 bronze badges

answered Dec 11, 2020 at 15:03

Bendemann's user avatar

BendemannBendemann

65712 silver badges27 bronze badges

2

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:PersonalIJSCodeprogram.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\Docspython.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.

Table of Contents
Hide
  1. What is permission denied error?

    1. How these permissions are defined?
  2. Reasons of permissionerror ERRNO 13 in Python

    1. Using folder path instead of file path while opening a file
    2. Trying to write to a file which is a folder
    3. Trying to write to a file which is already opened in an application
    4. File permission not allowing python to access it
    5. File is hidden with hidden attribute
  3. Conclusion

    1. Related Posts

Permission denied means you are not allowed to access a file. But why this happens? This is because a file has 3 access properties – read, write, and execute. And 3 sets of users – owner, group, and others. In this article we will look at different solutions to resolve PermissionError: [Errno 13] Permission denied.

What is permission denied error?

Suppose you have a file in your computer but you can’t open it. Strangely another user can open the same file. This is because you don’t have permission to read the content of that file.

Permission denied on files to protect them. For example, you have stored username & password for your database in a file so you never want it to be accessible to anyone except the database application and you. That’s why you will restrict it from other applications, software, processes, users, APIs etc.

In a system, root user can access everything. So, we seldom use the root account otherwise there is no meaning of security. A software running with root privilege can access your password file which you wanted to be secure. That’s why sudo should be used with caution.

How these permissions are defined?

There are 3 types of permissions – read, write and execute. With read permission a software, process, application, user etc. can read a file. Similarly, with write permission they can write to the file. Execute is used to run it.

Now the question is, how to apply these permissions to different software, users etc.? Well there are 3 types of users – owner, group, and others. So, you can assign 3 sets of permissions, like this –

User Description Permissions
Owner An account of system who we want to separately assign permissions r – read
w – write
x – execute
Group A set of multiple accounts, software, processes who can share the same permissions r – read
w – write
x – execute
Others All the other entities of system r – read
w – write
x – execute

Let’s get back to our password file example. Now you are into others user category because you are not the owner of the file and probably not the part of group. People use to give least permissions to the others because these are the access levels for everyone.

The password file won’t have any permission in others category. And trying to access that will result in permission error: permission denied.

Reasons of permissionerror ERRNO 13 in Python

Primarily these are the reasons of permissionerror: errno13 permission denied in Python –

  1. Using folder path instead of file path while opening a file.
  2. Trying to write to a file which is a folder.
  3. Trying to write to a file which is already opened in an application.
  4. File permission not allowing python to access it.
  5. File is hidden with hidden attribute.

Let’s understand each of these reasons one by one and check their solutions.

Using folder path instead of file path while opening a file

To open a file for reading or writing, you need to provide the absolute or relative path to the file in open function. Sometimes we create path of parent folder instead of file and that will lead to the permission error 13. Check out this code –

file = open("C:\users\akash\Python\Documents", "r")
file.close()

The output will be –

Traceback (most recent call last):
  File "jdoodle.py", line 2, in <module>
    file = open("C:\users\akash\Python\Documents", "r")
PermissionError: [Errno 13] Permission denied: 'C:\users\akash\Python\Documents'

The reason for the error in above code is that we have used C:usersakashPythonDocuments as path which is a directory. Instead we needed to use C:usersakashPythonDocuments\myFile.csv.

Trying to write to a file which is a folder

This is a common case. Suppose you want to write to a file using Python but a folder with same name exists at that location then Python will get confused and try to write to a folder. This is not a right behavior because folders are not files and you can’t write anything on them. They are used for holding files only.

Trying to write to a file which is a folder will lead to permission error errno 13. Check this code –

# Directory Structure
# 📂/
# |_ 📂Users
#    |_ 📁myFile

file = open("/Users/myFile", "w")
file.write("hello")
file.close()

The output will be –

Traceback (most recent call last):
  File "jdoodle.py", line 2, in <module>
    file = open("/Users/myFile", "r")
PermissionError: [Errno 13] Permission denied: '/Users/myFile'

In the above example we showed the directory structure and tried to write to myFile. But myFile is already a name of directory in the path. Generally, if a file doesn’t exist and we try to write to it then Python creates the file for us. But in this case there is already a directory with the provided name and Python will pick it. This will lead to permission error.

The solution to this problem is to either delete the conflicting directory or use a different file name.

Trying to write to a file which is already opened in an application

If a file is already opened in an application then a lock is added to it so that no other application an make changes to it. It depends on the applications whether they want to lock those files or not.

If you try to write to those files or more, replace, delete them then you will get permission denied error.

This is very common in PyInstaller if you open a command prompt or file explorer inside the dist folder, then try to rebuild your program. PyInstaller wants to replace the contents of dist but it’s already open in your prompt/explorer.

The solution to this problem is to close all the instances of applications where the file is opened.

File permission not allowing python to access it

In the above section we talked about file permissions. Python will be in others category if it is not set as user or in a group. If the file has restrictive permissions for others then Python won’t be able to access it.

Suppose the permission to the file is –

Owner – read, write, execute
Group – read, write
Others – none

Then only owner and group will be able to read and write to the file. Others will not be able to access it. Check out this image –

file permissions and setting group and owner

In this image the file owner is www, group is www, owner permissions are read+write, group permission is read only, while others have no permissions.

The solution to this problem is to either provide appropriate permission to the file for others, or add Python as owner or to the group.

Another solution is to run Python with root privilege.

File is hidden with hidden attribute

If your file is hidden then python will raise permission error. You can use subprocess.check_call() function to hide/unhide files. Check this code –

import subprocess

myPath = "/Users/myFile.txt"
subprocess.check_call(["attrib", "-H", myPath])

file_ = open(myPath, "w")

In the above code -H attribute is used to unhide the file. You an use +H to hide it again.

Conclusion

In this article we saw a number of reasons for Python to throw PermissionError: [Errno 13] Permission denied and discussed about their solutions with code examples. Follow the steps provided in article and you will be able to resolve this issue.

Python can only open, read from, and write to files if an interpreter has the necessary permissions. If you try to open, read from, or write to a file over which Python has no permissions, you’ll encounter the PermissionError: [errno 13] permission denied error.

In this guide, we discuss what this error means and why it is raised. We’ll walk through an example so you can learn exactly how to solve this error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

PermissionError: [errno 13] permission denied

Computers use file permissions to protect the integrity of files. Some files have restricted access by default. You can change the access permissions of a file at any time.

Let’s say you are working on an important program. You may only want that program to be readable by you. To accomplish this, you could modify the “read” permissions on all the files and folders in your program. This would limit access to your program.

Any file that you try to access from a Python program must be readable by the user or group that is running the file.

If you are running a Python script from a web server process, for instance, you would need to make sure that the user that owns the web server has access to all the files that you reference in your code.

An Example Scenario

We’re going to build a program that reads a list of NFL scores from a file into a program.

We have a file called afc_east.csv which contains the following:

Bills,4,0
Patriots,2,1
Dolphins,1,3
Jets,0,4

Our file is a CSV. We’re going to import the Python csv module into our code so we can work with the file:

Next, let’s open up our file in our Python program. We can do this using the csv.reader() statement:

with open("afc_east.csv", "r") as file:
	reader = csv.reader(file)
	for r in reader:
		print(r)

This code will open up the file called afc_east.csv in read mode. Then, the CSV reader will interpret the file. The CSV reader will return a list of values over which we can iterate. We then print each of these values to the console using a for loop and a print() statement so we can see the contents of our file line-by-line.

Let’s run our program to see if it works:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
	with open("afc_east.csv", "r") as file:
PermissionError: [Errno 13] Permission denied: 'afc_east.csv'

Our code returns an error.

The Solution

A PermissionError indicates that Python does not have the right permissions to access a file.

Let’s check the permissions of our file. We can do this using the ls -la command:

We can see that the afc_east.csv file is owned by the root user:

-rw-rw-rw-  1 root  staff  46 Oct  5 07:01 afc_east.csv

This is a problem because we don’t run Python as root. This means that Python cannot read our file. To fix this error, we need to change the ownership permissions of our file using the chown command:

chown james:admin afc_east.csv

This command makes the “james” user and the “admin” group the owners of the file.

Alternatively, we could change the permissions of the file using the chmod command:

This command makes our file readable and executable by everyone. The file is only writable by the owner. Let’s try to run our Python script again:

['Bills', '4', '0']
['Patriots', '2', '1']
['Dolphins', '1', '3']
['Jets', '0', '4']

Our code successfully prints out all of the scores from our file.

Conclusion

The PermissionError: [errno 13] permission denied error occurs when you try to access a file from Python without having the necessary permissions.

To fix this error, use the chmod or chown command to change the permissions of the file so that the right user and/or group can access the file. Now you have the skills you need to solve this error like a pro!

Код:

import zipfile, os
import shutil
a = os.listdir(path="D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive")
for i in a:
    s='D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive\'+str(i)
    b = os.listdir(path=s)
    for j in b:
        s1 = 'D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive\'+i+'\'+j
        shutil.copyfile(s1, "D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive — копия")
    os.remove('D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive\'+i)

Ошибка:

Traceback (most recent call last):
  File "C:UsersAlexPycharmProjectsuntitledиз папок.py", line 9, in <module>
    shutil.copyfile(s1, "D:домашкаG_ Arhangelskiy_-_Time_DraiveG_ Arhangelskiy_-_Time_Draive — копия")
  File "C:UsersAlexAppDataLocalProgramsPythonPython36libshutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'D:\домашка\G_ Arhangelskiy_-_Time_Draive\G_ Arhangelskiy_-_Time_Draive — копия'

Что делать?


  • Вопрос задан

    более трёх лет назад

  • 39353 просмотра

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

Я бы написал так:

import os
from shutil import copyfile, rmtree

SOURCE = 'D:\домашка\G_ Arhangelskiy_-_Time_Draive\G_ Arhangelskiy_-_Time_Draive'
DESTINATION = 'D:\домашка\G_ Arhangelskiy_-_Time_Draive\G_ Arhangelskiy_-_Time_Draive — копия'

files = [f.path for f in os.scandir(SOURCE) if f.is_file()]
for file in files:
    copyfile(file, DESTINATION)
rmtree(SOURCE)

Как опытный разработчик на Python могу дать совет:

  • Повторяющиеся значения выделить в отдельную переменную (лучше было бы в константу, но в Python нет констант). Это по поводу пути исходника, которую я выделил в SOURCE (есть такое соглашение, когда неизменяемые переменные пишут заглавными)
  • Для удаления пути рекурсивно, есть rmtree в модуле shutils, а так же os.scandir более удобен чем os.listdir
  • Установите линтер (flake8) и настройте свой редактор на использование его. По коду видно, что не используете линтер

Пригласить эксперта


  • Показать ещё
    Загружается…

04 февр. 2023, в 20:45

1000 руб./за проект

04 февр. 2023, в 20:44

20000 руб./за проект

04 февр. 2023, в 20:04

35000 руб./за проект

Минуточку внимания

  1. What Is the IOError: [Errno 13] Permission denied in File Handling in Python
  2. How to Fix the IOError: [Errno 13] Permission denied in Python
  3. How to Use the chmod Command to Change the Permissions of a File in Python

IOError: [Errno 13] Permission Denied in Python

It is common to get IOError because we humans mostly interact with the GUI of a computer; we understand the difference between folders, files, compressed files or applications from the visuals.

We have interacted with folders, files, compressed files or applications so often that now our brains sometimes do not process to differentiate among these.

But on the other hand, you have to feed everything to computers they do not understand the visuals only; rather, you have to provide the complete details.

What Is the IOError: [Errno 13] Permission denied in File Handling in Python

In file handling, you need to provide the complete path of the file you want to access; otherwise, you will get the IOError. If you want to open a file but have provided the path of the folder instead, you will face the IOError: [Errno 13] Permission denied.

Below is a code example of the error in Python.

# opening file
f = open("E:ProjectsTest_folder", "r")

Output:

PermissionError: [Errno 13] Permission denied: 'E:\Projects\Test_folder'

In the above example, we are trying to open the Test_folder in reading mode, but this has thrown the PermissionError: [Errno 13] Permission denied.

How to Fix the IOError: [Errno 13] Permission denied in Python

To fix this, you need to enter the right path to the file you want to access, not the folder. Let’s say we have two files in the Test_folder.

import os
# Folder Path
folder_path = "E:Client Project ReportTest_folder"

# display all files in a folder
print(f"All files in the Test_folder aren{os.listdir(folder_path)}")

# file path
file_path = "E:Client Project ReportTest_folderTest_file_1.txt"

# read file
f = open(file_path, "r")
print(f"n{f.read()}")

# file closed
f.close()

Output:

All files in the Test_folder are
['Test_file_1.txt', 'Test_file_2.txt']

Hi There!
This is test file 1

After providing the path of the file, the error is resolved. Also, it is a good practice to close the opened files in Python so no one can further read and write that file until and unless it is opened again, and if you are trying to write or read a closed file, it will raise a ValueError.

Although Python automatically closes a file when the reference object of the file is assigned to another file. But still, it is a good practice to close a file with the close() function.

In addition, you can also use the exception handling mechanism like try-catch blocks to catch such errors and keep your program safe from crashing.

How to Use the chmod Command to Change the Permissions of a File in Python

As discussed, the IOError: [Errno 13] Permission denied occurs when you try to open a file that is not permitted.

Let’s say you want to open a folder that is not allowed to your access, but still, you try to write a script in Python to open that folder, the permission to access the folder will be denied, and the Python compiler will throw the error.

To resolve this error, we can use the chmod command, which stands for change mode. The chmod() requires two arguments, the path of the file/folder you want to access and the file mode.

The chmod command is used to change the file permission of a file, and it is done by changing the permission flags of a particular file.

The permission flags are represented by a three-digit octal value used to specify read, write, and execute permissions for the file owner, the file group, and all other users.

Syntax of chmod:

The command takes two arguments:

  1. The first is the path to the file whose permissions you want to change.
  2. And the second is the permission you want to set.

Let’s say you want to give read and write permissions to everyone for a file named filename; you would use the following command.

chmod 777 filename

The Python script for the above command would be:

import os
os.chmod('my_file', 0o777)

This piece of code can also be represented as:

import os
import stat
path = ('E:Projectfile1.txt')

# stat.S_IRWXU --> All permissions (Read, write, and execute) to the owner
# stat.S_IRWXG --> All permissions (Read, write, and execute) to group
# stat.S_IRWXO --> All permissions (Read, write, and execute) to others

print(os.chmod(path, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO))

This would give everyone read, write, and execute permissions of the specific file.

What Does the Three Octal Number Represent in chmod

The permissions of a file can be represented using an octal number. The octal number is made up of three digits, each of which represents different permission.

  1. The first digit represents the owner’s permission.
  2. The second digit represents the group’s permissions.
  3. And the third digit represents the permissions for others.

The permissions of a file can be changed by using the chmod command with the octal number representing the desired permissions.

For example, to give the owner of a file read, write, and execute permissions while giving the group and others read and execute permissions only, the octal number 755 can be used.

hey guys… having an issue here… wondering if anyone has any ideas

Running auto-py-to-exe v2.27.0
Building directory: C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663
Provided command: pyinstaller --noconfirm --onedir --console  "C:Usersbdawg.LAPTOP-2CKTEBU7Bot BusinessDentist Customer"
Recursion Limit is set to 5000
Executing: pyinstaller --noconfirm --onedir --console C:Usersbdawg.LAPTOP-2CKTEBU7Bot BusinessDentist Customer --distpath C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663application --workpath C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663build --specpath C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663

238375 INFO: PyInstaller: 5.4.1
238386 INFO: Python: 3.10.9
238401 INFO: Platform: Windows-10-10.0.22621-SP0
238418 INFO: wrote C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663Dentist Customer.spec
238435 INFO: UPX is not available.
238450 INFO: Extending PYTHONPATH with paths
['C:\Users\bdawg.LAPTOP-2CKTEBU7\Bot Business']
239589 INFO: checking Analysis
239593 INFO: Building Analysis because Analysis-04.toc is non existent
239609 INFO: Reusing cached module dependency graph...
239649 INFO: Caching module graph hooks...
239665 WARNING: Several hooks defined for module 'numpy'. Please take care they do not conflict.
239796 INFO: running Analysis Analysis-04.toc
239806 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0python.exe
239821 WARNING: lib not found: api-ms-win-appmodel-runtime-l1-1-0.dll dependency of C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0python.exe
240051 INFO: Analyzing C:Usersbdawg.LAPTOP-2CKTEBU7Bot BusinessDentist Customer
An error occurred while packaging
Traceback (most recent call last):
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesauto_py_to_exepackaging.py", line 131, in package
    run_pyinstaller()
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstaller__main__.py", line 179, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstaller__main__.py", line 60, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerbuildingbuild_main.py", line 962, in main
    build(specfile, distpath, workpath, clean_build)
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerbuildingbuild_main.py", line 884, in build
    exec(code, spec_namespace)
  File "C:UsersBDAWG~1.LAPAppDataLocalTemptmpyqt33663Dentist Customer.spec", line 7, in <module>
    a = Analysis(
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerbuildingbuild_main.py", line 409, in __init__
    self.__postinit__()
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerbuildingdatastruct.py", line 173, in __postinit__
    self.assemble()
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerbuildingbuild_main.py", line 572, in assemble
    priority_scripts.append(self.graph.add_script(script))
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerdependanalysis.py", line 268, in add_script
    self._top_script_node = super().add_script(pathname)
  File "C:Usersbdawg.LAPTOP-2CKTEBU7AppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesPyInstallerlibmodulegraphmodulegraph.py", line 1415, in add_script
    with open(pathname, 'rb') as fp:
PermissionError: [Errno 13] Permission denied: 'C:\Users\bdawg.LAPTOP-2CKTEBU7\Bot Business\Dentist Customer'

Понравилась статья? Поделить с друзьями:
  • Permission denied publickey ssh ошибка windows
  • Permission denied publickey keyboard interactive windows
  • Permission denied please try again ssh windows
  • Perl utf 8 to windows 1251
  • Peripheral bluetooth driver windows 7 download