python删除文件一行数据、不使用临时文件_使用python脚本删除Windows Temp文件

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.

解决方案

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值