您好,当我运行这个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'
问题在于当我在另一台笔记本电脑上运行时它可以工作。 我的同事尝试在他们的电脑上运行它,但它也无法工作,所以我不确定为什么会出现这个错误。
if keyword in content
移到第一个with
子句的范围之外。 - BoarGules