2009-10-12 95 views

回答

44

使用shutil.rmtree

import shutil 

shutil.rmtree(path) 

對於如何處理和/或忽略錯誤的詳細信息,請參閱the documentation

+13

如果目錄中有文件,這將失敗。看dghubble的帖子。 – CornSmith 2014-05-02 19:43:22

7

你想​​

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

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

32

標準庫包括shutil.rmtree這一點。默認情況下,

shutil.rmtree(path) # errors if dir not empty 

將給OSError: [Errno 66] Directory not empty: <your/path>

您可以忽略錯誤刪除目錄及其內容呢:

shutil.rmtree(role_fs_path, ignore_errors=True) 

可以通過同時傳遞onerrror=<some function(function, path, excinfo)>執行更復雜的錯誤處理。

+4

'ignore_errors = True'表示不會刪除目錄。 – ostrokach 2015-09-03 17:50:36

+0

ignore_errors = True是報價 – 2015-09-09 05:53:59

+0

它適用於我。 – Jerome 2018-01-04 07:14:16