繁体   English   中英

使用python删除临时文件夹中的所有文件

[英]Deleting all files in temp folder Using python

这是我删除临时文件夹所有文件的代码,但由于正在使用临时文件,我想跳过所有无法删除的文件并删除其余所有文件。 谁能建议我更好的代码?

def del_tmp_files():
    username = getpass.getuser()
    del_path = "C:\\Users\\" + username + "\\AppData\\Local\\Temp"
    shutil.rmtree(del_path)
    print("Del Path" + del_path)
    return

您可以实现 try except 框架来删除文件,这里是伪代码:

cd temp directory
fileList = get all the filenames in the temp directory
for file in fileList:
  try:
    delete file
  except:
    pass

shutil.rmtree ignore_errors=Trueshutil.rmtree一起shutil.rmtree

def rmtree(path, ignore_errors=False, onerror=None):

递归删除目录树。

 If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.
import getpass
import shutil

def del_tmp_files():
    username = getpass.getuser()
    del_path = "C:\\Users\\" + username + "\\AppData\\Local\\Temp"
    shutil.rmtree(del_path, ignore_errors=True)
    print("Del Path" + del_path) 
    return

del_tmp_files()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM