Namechange
Namechange

Reputation: 29

Deleting Temp folder in Windows, TypeError: join() argument must be str or bytes, not 'list'

I'm trying to delete the Temp folder in Windows with python script but get this error:

TypeError: join() argument must be str or bytes, not 'list'

This is my script:

is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin==False:
    messagebox.showerror("Error", message="You need to run this program as "
                                          "administrator to cleanup your pc!")
else:
    user=(os.path.expanduser("~"))
    tmp_folder=(user+"/AppData/Local/Temp")
    listdir=os.listdir()
    path=os.path.join(tmp_folder, listdir)
    os.remove(path)

What is my mistake here?

Upvotes: 0

Views: 149

Answers (1)

Rolv Apneseth
Rolv Apneseth

Reputation: 2118

As it says, os.path.join() takes string arguments, but you're passing it a list. You are also, from the looks of it, trying to remove a folder with os.remove but that can only be used for individual files.

Try something like this for your else block instead:

user = os.path.expanduser("~")
tmp_folder = os.path.join(user, "/AppData/Local/Temp")

for root, dirs, files in os.walk(tmp_folder, topdown=False):
    for file in files:
        try:
            os.remove(file)
        except OSError:
            print(f"Could not delete the file at {file}")

This makes use of os.walk() to go through the files in the directory and delete them individually. Let me know if this works for you and does what you want it to.

Upvotes: 1

Related Questions