3

Hello so I am getting this error permission denied when I run this python script.

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

the error I am getting is

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'

The problem is when I run this on a different laptop it works. My coworker tried running it on theirs and it doesn't work either so I am not sure why it's giving me this error.

Rafi Hasan
  • 69
  • 1
  • 7

1 Answers1

1

The problem is that you are attempting to open a directory (in this case, .vscode) as if it were a file. You can't do this, and on Windows you will get a permission-denied error if you try. Running your script as administrator will make no difference.

What should your script do when it encounters a directory? Ignore it altogether, or recursively process the files within the directory?

If you just need to ignore directories, call os.path.isfile with the filename you get from os.listdir(), and if os.path.isfile returns False, skip that filename. If however you need to recursively process files, look at os.walk instead.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104