【问题标题】:PermissionError: [Errno 13] Permission deniedPermissionError: [Errno 13] 权限被拒绝
【发布时间】:2016-07-25 21:21:44
【问题描述】:

我收到此错误:

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'

运行时:

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!!')

谁能告诉我我做错了什么?

规格: Python 3.4.4 x86 Windows 10 x64

【问题讨论】:

  • 不应该place_to_save 只是goodbye.txt?我不确定 Windows 的行为如何,但在 Linux 上,您将写入根目录 (/),这始终是个坏主意。您应该使用os.path.join(directory, selected_text),而不是手动字符串操作。
  • 尝试open(place_to_save, 'w+') 而不是open(place_to_save, 'wb')。我记得看到其他一些关于同一问题的 SO 帖子,
  • 一个 MCVE *.com/help/mcve 应该是一行:open('/goodbye.txt', 'wb')。如果这也引发了,那么 tkinter 是无关紧要的,应该作为标签删除。这应该用操作系统标记,因为这相关的。
  • print(directory, selected_text, place_to_save) 的输出是什么?我的猜测是 directory 出于某种原因是一个空字符串。我会尝试将initialdir=r'c:/' 添加到filedialog.askdirectory 通话中。
  • @Mixone 我认为这是因为代码不是最少的。唯一相关的行是 ` with open(place_to_save, 'wb') as file:` 和 也许 路径本身。堆栈跟踪也未满。

标签: python python-3.x windows tkinter permission-denied


【解决方案1】:

如果您试图打开一个文件,但您的路径是一个文件夹,就会发生这种情况。

这很容易发生错误。

要防御这种情况,请使用:

import os

path = r"my/path/to/file.txt"
assert os.path.isfile(path)
with open(path, "r") as f:
    pass

如果路径实际上是文件夹,则断言将失败。

【讨论】:

  • 我希望原来的提问者能接受这个作为答案。关于这个错误有很多很多问题,这是唯一似乎真正正确的答案。尽管文件具有正确的权限设置,但通常会发生此错误,因此答案必须是其他内容。就是这样。
【解决方案2】:

在 Windows 上获得管理员execution 权限的主要方法主要有三种。

  1. 以管理员身份从cmd.exe 运行
  2. 创建快捷方式以使用提升的权限执行文件
  3. 更改python 可执行文件的权限(不推荐)

A) 以管理员身份运行 cmd.exe

由于在 Windows 中没有 sudo 命令,您必须以管理员身份运行终端 (cmd.exe) 才能达到与 sudo 等效的权限级别。您可以通过两种方式做到这一点:

  1. 手动

    • C:\Windows\system32 中查找cmd.exe
    • 右键单击它
    • 选择Run as Administrator
    • 然后它将在目录C:\Windows\system32 中打开命令提示符
    • 前往您的项目目录
    • 运行你的程序
  2. 通过快捷键

    • 按 windows 键(通常在 altctrl 之间)+ X
    • 将出现一个包含各种管理员任务的小弹出列表。
    • 选择Command Prompt (Admin)
    • 前往您的项目目录
    • 运行你的程序

通过这样做,您将以管理员身份运行,因此此问题不应持续存在

B) 创建具有提升权限的快捷方式

  1. python.exe 创建快捷方式
  2. 右键单击快捷方式并选择Properties
  3. 将快捷方式目标更改为"C:\path_to\python.exe" C:\path_to\your_script.py"
  4. 点击快捷方式属性面板中的“高级”,然后点击“以管理员身份运行”选项

delphifirst 在this question提供的答案

C) 更改python 可执行文件的权限(不推荐)

这是可能的,但我强烈建议您不要这样做。

它只涉及找到python 可执行文件并将其设置为每次都以管理员身份运行。可能并且可能会导致文件创建(它们将仅是管理员)或可能不需要管理员才能运行的模块等问题。

【讨论】:

  • 如果 PyCharm 发生这种情况怎么办?我无法授予 python.exe 管理员权限,因为这是一台工作计算机。
  • 在这种情况下,您可能需要联系您的 IT 支持团队。或者只是将文件创建/删除移动到您在工作电脑上具有写入权限的目录
  • 如果可以的话,也可以尝试以管理员身份运行 PyCharm,而不是 python.exe
  • @Mixone 为什么 OP 需要管理员权限?如果他拥有目标文件夹,并且拥有程序,那么级别肯定匹配吗?如何调试您正在运行的级别以及任何特定目标所需的级别?
【解决方案3】:

确保您尝试写入的文件首先关闭。

【讨论】:

  • 请详细解释您的解决方案,以便更好地了解方法
  • 我在 windows 中运行 pydev 项目,这个解决方案对我来说很好
【解决方案4】:

更改要保存到的目录的权限,使所有用户都有读写权限。

【讨论】:

  • 谢谢。当我以管理员身份运行 anaconda 提示符时,它可以工作。
【解决方案5】:

您可以以管理员身份运行 CMD 并使用 cacls.exe 更改目录的权限。例如:

cacls.exe c: /t /e /g everyone:F # means everyone can totally control the C: disc

【讨论】:

    【解决方案6】:

    问题可能出在您要打开的文件的路径上。尝试打印路径,看看是否正常 我有类似的问题

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

    但添加此代码后:

    nofilenametxt=filenm.split('/')
    nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
    if (len(nofilenametxt)==0):
        filenm=("{}index.html").format(filenm)
    

    【讨论】:

      【解决方案7】:

      我在运行程序以写入已打开的文件时收到此错误。在我关闭文件并重新运行程序后,程序运行没有错误并按预期工作。

      【讨论】:

      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      【解决方案8】:

      如果您打开了文件,例如:.txt、.csv;先关闭文件再运行代码

      【讨论】:

      • 确实,如果文件在 Excel 中打开,你不能open它。
      【解决方案9】:

      我遇到了类似的问题。我想可能是系统的问题。但是,使用 shutil 模块中的 shutil.copytree() 为我解决了这个问题!

      【讨论】:

        【解决方案10】:

        在我的情况下,问题是我隐藏了文件(文件具有隐藏属性):
        如何在 python 中处理问题:

        编辑:突出显示不安全的方法,谢谢 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
        
        

        【讨论】:

        【解决方案11】:

        我遇到了类似的问题。我在 Windows 上使用 Anaconda,我解决了如下问题: 1)从开始菜单中搜索“Anaconda prompt” 2)右键单击并选择“以管理员身份运行” 3)按照安装步骤...

        这会处理权限问题

        【讨论】:

          【解决方案12】:

          就我而言。我只是隐藏了.idlerc 目录。 所以,我所要做的就是到那个目录,然后让recent-files.lst unhidden,问题就解决了

          【讨论】:

            【解决方案13】:

            这是我遇到错误的方式:

            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
            

            如果用户输入一个包含多个元素的文件路径,例如

            C:\\Users\\Name\\Desktop\\Folder
            

            但我认为它可以与像这样的输入一起使用

            file.txt
            

            只要file.txt在python文件的同一目录下。但是不,它给了我这个错误,我意识到正确的输入应该是

            .\\file.txt
            

            【讨论】:

            • 或者你可以使用path = os.path.abspath(path)
            • 另外,您可以(并且应该)使用os.path.sep,或者更好地使用os.path.join,而不是所有的“\\”
            【解决方案14】:

            正如@gulzar 所说,我在位于Z:\project\test.py 的python 脚本中编写文件'abc.txt' 时遇到问题:

            with open('abc.txt', 'w') as file:
                file.write("TEST123")
            

            实际上,每次我运行脚本时,它都想在我的 C 盘而不是 Z 中创建一个文件 所以我只指定了文件名的完整路径:

            with open('Z:\\project\\abc.txt', 'w') as file: ...
            

            效果很好。我不必在 Windows 中添加任何权限或更改任何内容。

            【讨论】:

              【解决方案15】:

              另一个对我有帮助的选择是使用 pathlib:

              from pathlib import Path
              p = Path('.') ## if you want to write to current directory
              with open(p / 'test.txt', 'w') as f:
                  f.write('test message')
              
              

              【讨论】:

                【解决方案16】:

                这是一个棘手的问题,因为错误消息会引诱您远离问题所在。

                当您在权限错误的根部看到导入模块的"__init__.py" 时,您有命名冲突。我睡了一瓶朗姆酒,顶部有"from tkinter import *"的文件。在 TKinter 内部,有一个变量、一个类或一个函数的名称,这些名称已经在脚本的其他任何地方使用。

                其他症状是:

                1. 脚本运行后立即提示错误。
                2. 该脚本可能在以前的 Python 版本中运行良好。
                3. 用户 Mixon 关于管理员执行权限的长篇文章根本没有影响。从控制台或其他软件访问代码中提到的文件不会出现错误。

                解决方案: 将导入行更改为“import tkinter”,并将命名空间添加到代码中的 tkinter 方法中。

                【讨论】:

                  【解决方案17】:

                  这个错误其实在使用keras.preprocessing.image时也会出现,例如:

                  img = keras.preprocessing.image.load_img(folder_path, target_size=image_size)
                  

                  会抛出权限错误。奇怪的是,如果您首先导入库:from keras.preprocessing import image,然后才使用它,问题就解决了。像这样:

                  img = image.load_img(img_path, target_size=(180,180))
                  

                  【讨论】:

                  • 我打算编辑您的命名以使其具有凝聚力,然后注意到您收到了folder_path 的错误,而没有收到img_path 的错误。这让我相信 Keras 没有被窃听,你的问题的真正解决方案是 *.com/a/62244490/913098