简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM