2

Can you help me how can i delete all the files under the Windows/Temp files?? Below are my scripts but it doesn't work at all.

import os
import subprocess
recPath = 'C:\\Windows\\Temp'
ls = []
if os.path.exists(recPath):
    for i in os.listdir(recPath):
        ls.append(os.path.join(recPath, i))
else:
    print 'Please provide valid path!'

paths = ' '.join(ls)
pObj = subprocess.Popen('rmdir C:\\Windows\\Temp\\*.* /s /q *.*'+paths, shell=True, stdout = subprocess.PIPE, stderr= subprocess.PIPE)
rTup = pObj.communicate()
rCod = pObj.returncode
if rCod == 0:
    print 'Success: Cleaned Windows Temp Folder'
else:
    print 'Fail: Unable to Clean Windows Temp Folder'

Thank you in advance.

Aouie
  • 119
  • 2
  • 8
  • 17
  • what means `doesn't work` ? We can't read in your mind. Do you get error message ? Always show full message in question. – furas Nov 12 '16 at 02:43
  • hi. apologies for the confusion. btw, there's no error message display after i execute in the command. – Aouie Nov 12 '16 at 02:46
  • rmdir is mean for remove directory, you might wanna try with command del instead, also you might not need the paths since you plan to remove all files, try 'del C:\\Windows\\Temp\\*.* /s /q ' – Skycc Nov 12 '16 at 02:49
  • print full line `rmdir ...` and try it in command. print variables to see what you get. – furas Nov 12 '16 at 02:51
  • `*.*'+paths` this doesn't add space between `*.*` and paths – furas Nov 12 '16 at 02:52
  • hi Skycc. thank you for suggesting but can you please give me a sample code on how to use it. Sorry but im a newbie in using python language. – Aouie Nov 12 '16 at 02:52

3 Answers3

3

using windows command del to remove all files in dir with wildcard . This will delete all files recursively within it, however it will leave the empty subfolder there

import os, subprocess
del_dir = r'c:\windows\temp'
pObj = subprocess.Popen('del /S /Q /F %s\\*.*' % del_dir, shell=True, stdout = subprocess.PIPE, stderr= subprocess.PIPE)
rTup = pObj.communicate()
rCod = pObj.returncode
if rCod == 0:
    print 'Success: Cleaned Windows Temp Folder'
else:
    print 'Fail: Unable to Clean Windows Temp Folder'

change the 1st line to below to delete whole directory tree of Windows\Temp.This will remove everything include the Temp folder itself if success, recreate parent directory afterwards

del_dir = r'c:\windows\temp'
pObj = subprocess.Popen('rmdir /S /Q %s' % del_dir, shell=True, stdout = subprocess.PIPE, stderr= subprocess.PIPE)
# recreate the deleted parent dir in case it get deleted
os.makedirs(del_dir)

Else, rmtree from shutil should be a pretty good choice, ignore_errors set to ignore all the errors in middle and continue until all directory tree complete

import shutil, os
del_dir = r'c:\windows\temp'
shutil.rmtree(del_dir, ignore_errors=True)
# recreate the deleted parent dir in case it get deleted
os.makedirs(del_dir)

Another option to iterate over directory to be deleted

import os,shutil
del_dir = r'c:\windows\temp'
for f in os.listdir(del_dir):
    if os.path.isfile(f):
        os.remove(f)
    elif os.path.isdir(f)
        shutil.rmtree(f, ignore_errors=True)

change the del_dir accordingly to any directory of interest

You are dealing with windows folder, beware to set the directory to delete carefully, you would not want to mistakenly put del_dir = r'c:\windows'

Skycc
  • 3,496
  • 1
  • 12
  • 18
  • hi Skycc. Thanks man for the code. However it didn't delete all the folders and subfolders on the Windows\Temp. – Aouie Nov 12 '16 at 03:29
  • try the rmdir cmd i just added, actually the shutil cmd with ignore_errors set to True should works, it will try to delete what ever it can delete included empty subfolder leaving those fail to delete behind – Skycc Nov 12 '16 at 03:59
  • Hi Skycc. I tried to apply that code to delete the Prefetch folder under C:\Windows. The good news is it delete everything on the prefetch folder but the bad news is it also deleted the Prefetch folder. How can i prevent to do not delete the Prefetch folder. – Aouie Nov 12 '16 at 05:17
  • Not a very good answer, after deleting, recreate the folder with os.makedirs(r'c:\windows\prefetch') or use os.listdir(r'c:\windows\prefetch') then use os.remove(file) if its a file else use shutil.rmtree(dir) for dir – Skycc Nov 12 '16 at 05:56
  • How can i apply that script to my actual script bro? Can you help me? – Aouie Nov 12 '16 at 06:04
  • Checkout added answer bro :) – Skycc Nov 12 '16 at 06:29
  • Sure thing bro. Thanks. :) – Aouie Nov 12 '16 at 06:36
  • Hi Skycc. Upon trying the updated scripts. Still it delete the Temp Folder and didnt create as expected. I think because the scripts needs an admin privilege to create a directory on Windows. How can we create a script with an admin privilege? – Aouie Nov 12 '16 at 09:15
  • Weird, when you run the script as admin, when you able to delete, you should be able to create, how about trying the last solution i provide that iterate though directory, that doesn't remove the source dir – Skycc Nov 12 '16 at 09:17
  • Or you could try os.system('mkdir %s' % del_dir) instead of os.makedirs – Skycc Nov 12 '16 at 09:23
  • can you please check my other concerns bro?? here is the link: http://stackoverflow.com/questions/40560050/disk-defrag-and-disk-clean-up-using-python-script – Aouie Nov 13 '16 at 04:02
  • Great, sure, will check when free – Skycc Nov 13 '16 at 04:03
  • there's a typo in the 4th solution (removing files and subfolders with python) : the `else` condition is missing a semicolon – jeromes Jul 31 '23 at 13:58
1

Use shutil.

import shutil

shutil.rmtree(r"C:\Windows\Temp")
Batman
  • 8,571
  • 7
  • 41
  • 80
  • hi Batman. thank you for your help. upon trying the code that you gave. it deleted some files but not all the files and folders in the windows\temp folder. – Aouie Nov 12 '16 at 02:49
  • Weird. What happens if you call `os.unlink(path)` on one of the remaining files? – Batman Nov 12 '16 at 02:54
  • i guess you don't have permission to remove all files in temp, some might be in use. Try if you are able to remove that manually – Skycc Nov 12 '16 at 02:55
  • hi Batman. it didn't do anything when i used the os.unlink(path). – Aouie Nov 12 '16 at 03:03
  • I'm going to guess that they're in use then. Try rebooting the machine and see if they're removable afterwards. – Batman Nov 12 '16 at 03:10
  • try goto temp dir, right click delete any of files that fail to delete see if you were able to do that, if it fail, script method will fail also – Skycc Nov 12 '16 at 03:16
  • hi skycc. upon trying it manually, there are some files that fail to delete. can you please help to delete all the files including the folders ans sub folders and ignore all the files/folders that fail to delete?? – Aouie Nov 12 '16 at 03:37
0

You might want to hard-code the path.

    import os
    import shutil
    del_dir = r'C:\Windows\Temp'
    for f in os.listdir(del_dir):
        if os.path.isfile(r'C:\Windows\Temp\\'+f):
            os.remove(r'C:\Windows\Temp\\'+f)
        elif os.path.isdir(r'C:\Windows\Temp\\'+f):
            shutil.rmtree(r'C:\Windows\Temp\\'+f, ignore_errors=True)
Akash
  • 100
  • 1
  • 10