且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用python脚本删除Windows Temp文件

更新时间:2023-12-05 19:25:40

使用Windows命令del删除目录中的所有文件使用通配符
。这将递归删除其中的所有文件,但是它将在其中保留空的子文件夹

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'

将第一行更改为下面以删除Windows\Temp的整个目录树。如果成功,它将删除包括Temp文件夹本身在内的所有内容,然后重新创建父目录

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)

否则,shutil的rmtree应该是一个不错的选择,ignore_errors设置为忽略中间的所有错误并继续直到所有目录树完成为止

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)

相应地将del_dir更改为任何感兴趣的目录

change the del_dir accordingly to any directory of interest

您正在处理Windows文件夹,注意将目录设置为仔细删除,您不要误将del_dir = r'c :\windows’