使用python代码删除临时文件

时间:2017-08-09 13:18:18

标签: python-2.7

我想删除临时文件但是如果我运行我的代码它只是完全删除Temp文件夹,我想删除文件 在临时文件夹中

import os
import shutil
from shutil import rmtree

yourpath = 'C:\\Users\\SHIVAPRASAD\\Appdata\Local\Temp'
folder_size=0


for (root, dirs, files) in os.walk(yourpath):
    for name in files:
    filename = os.path.join(root, name)
    folder_size +=os.path.getsize(filename)
    print "Folder size in mb is\n",str((folder_size/(1024*1024.0)))


 for (root, dirs, files) in os.walk(yourpath):
      for name in files:
      print (os.path.join(root,name))


print 'Do u want to delete temporavary file of size',str((folder_size/(1024*1024.0))),'MB'' ' 'y/n'
n=raw_input()
if n=='y':
  shutil.rmtree(r'C:\\Users\\SHIVAPRASAD\\Appdata\Local\Temp')
  print 'succesfully removed the temp files'
else:
   print 'you have not removed the temporavary file'

1 个答案:

答案 0 :(得分:0)

来自https://docs.python.org/2/library/shutil.html

  

shutil.rmtree(path [,ignore_errors [,onerror]])

     

删除整个目录树;

这是你的计划所做的,但不是你想要的

使用os.remove()您可以删除文件:

for (root, dirs, files) in os.walk(yourpath):
    for name in files:
        print os.path.join(root, name)
    print 'Do u want to delete temporary file of size', str((folder_size/(1024*1024.0))), 'MB'' ' 
    n = raw_input('y/n >')
    if n =='y':
        for file in  files:
            os.remove(os.path.join(root, file))
        print 'succesfully removed the temp files'
    else:
        print 'you have not removed the temporary files'