如何解决 PermissionError: [Errno 13] 权限被拒绝

时间:2021-06-28 19:18:07

标签: python debugging

你好,当我运行这个 python 脚本时,我得到了这个错误权限被拒绝。

import os

keyword = input("Enter Keyword to search : ")
replacement = input("Enter replacement string : ")

for filename in os.listdir():
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
       content = f.read()
       if keyword in content:
           with open(os.path.join(os.getcwd(), filename), 'w') as fw: # open in write mode
               writecontent = content.replace(keyword, replacement)
               fw.write(writecontent)
               print(f"Keyword {keyword} found and replaced in file : {filename}")


input("Press Enter to exit")

我得到的错误是

Traceback (most recent call last):
  File "c:/Users/smraf/Desktop/Test Python/script.py", line 9, in <module>
    with open(os.path.join(os.getcwd(), filename), 'r') as f:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\username\\Desktop\\Test Python\\.vscode'

问题是当我在另一台笔记本电脑上运行它时它可以工作。我的同事尝试在他们的身上运行它,但它也不起作用,所以我不确定为什么会出现此错误。

1 个答案:

答案 0 :(得分:0)

问题在于您试图打开一个目录(在本例中为 .vscode),就好像它是一个文件一样。您不能这样做,并且在 Windows 上,如果您尝试,您将收到权限被拒绝的错误。以管理员身份运行脚本没有任何区别。

你的脚本遇到目录时应该怎么做?完全忽略它,还是递归处理目录中的文件?

如果您只需要忽略目录,请使用您从 os.listdir() 获得的文件名调用 os.path.isfile,如果 os.path.isfile 返回 False,则跳过该文件名。但是,如果您需要递归处理文件,请查看 os.walk