0

I was working on a project where a recursive program would look through my computer to find a specific file. When it tries to open the recycle bin, the following error is produced: The function that produces this error is this:

def containsFile(path, filename):
    print(path, os.access(path, os.R_OK))
    for thing in os.listdir(path):
        if(thing == filename):
            return os.path.join(path, filename)
        return False

I tried to test permissions for the file by printing os.access(path, os.R_OK) to the console, but it says that I have access to the recycle bin in the console. Is there a way to check for files/folders I don't have access to? Thanks in advance.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
h0gs
  • 13
  • 4
  • "check for files/folders I don't have access to"? What kind of "check" might be done without any access? – Scott Hunter Mar 24 '23 at 19:39
  • Reading a file and enumerating a directory are different permissions, if I recall correctly. And in this case, it's better to ask forgiveness than permission; you might just catch the `PermissionError` or whatever it's throwing and handle it; *that's* your check. – Silvio Mayolo Mar 24 '23 at 19:47

1 Answers1

1

Wrap the call to containsFile in a try/except block to catch the Permission Error. The paradigm in Python is to try to do the possibly bad thing and catch the exception aka "It's Easier to Ask Forgiveness than Permission" aka EAFP

def main():
    ...
    try:
        result = containsFile(path, filename)
    except PermissionError as e:
        print(f"Unable to search {path} : {e}")
        # Maybe add something here to skip ahead to the next path?
    else:
        # Handle the result True/False
    ....
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12