如何解决PermissionError: [Errno 13]权限被拒绝的问题。

3

您好,当我运行这个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'

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


尝试以管理员身份运行 - It_is_Chris
在我看来,你正在写入一个仍然处于读取状态的文件。将 if keyword in content 移到第一个 with 子句的范围之外。 - BoarGules
1个回答

1
问题在于你试图像打开文件一样打开一个目录(在这种情况下是 .vscode),但你不能这样做,如果在Windows上尝试,会出现权限被拒绝的错误。以管理员身份运行脚本也没有任何区别。
当你的脚本遇到一个目录时应该怎么办?完全忽略它,还是递归处理目录中的文件?
如果你只需要忽略目录,请使用从os.listdir()获取的文件名调用os.path.isfile,如果os.path.isfile返回False,则跳过该文件名。但是,如果你需要递归处理文件,请查看os.walk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接