2009-10-12 130 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