user2926827 user2926827 - 26 days ago 7
Python Question

Deleting Windows Temp Files using python script

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.

Answer

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

pObj = subprocess.Popen('del /S /Q /F C:\\Windows\\Temp\\*.*', 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

pObj = subprocess.Popen('rmdir /S /Q C:\\Windows\\Temp', shell=True, stdout = subprocess.PIPE, stderr= subprocess.PIPE)

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
shutil.rmtree(r"C:\Windows\Temp", ignore_errors=True)