[英]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=True
與shutil.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.