Search code examples
pythondelete-fileremoveall

Deleting files from download folder using Python


I am trying to delete files from my download folder but I get and error that read PermissionError: [WinError 5] Access is denied: 'C:\\Users\\Downloads'

I tried running Visual Studio as admin and adding a code to elevate privileges but I still get the error

my code is

ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)

def deleteFiles():
    folder = "C:\\Users\\Downloads"
    for f in glob.glob(folder):
        os.remove(f)
    return;

deleteFiles()

can anyone help with getting these files deleted? Thanks


Solution

  • glob.glob() returns a list of all filenames matching a wildcard expression. i.e. if you passed it '/tmp/*.py', it might return the list ['/tmp/bar.py', '/tmp/baz.py', 'tmp/foo.py'].

    You passed it a string which contains no wildcard characters, so it just returned the original string back to you, so your code ended up calling os.remove('C:\\Users\\Downloads').