问题描述
这是我的代码,用于删除临时文件夹中的所有文件,但是由于使用了临时文件,我想跳过所有无法删除的文件,并删除其余所有文件。 谁能建议我更好的代码?
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 try框架来删除文件,这是伪代码:
cd temp directory
fileList = get all the filenames in the temp directory
for file in fileList:
try:
delete file
except:
pass
,
将 ignore_errors=True
与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()