Come eliminare una directory probabilmente non vuota in Python.python: elimina la directory non vuota
La directory può avere sottodirectory nidificate con molti livelli profondi.
Come eliminare una directory probabilmente non vuota in Python.python: elimina la directory non vuota
La directory può avere sottodirectory nidificate con molti livelli profondi.
Uso shutil.rmtree
:
import shutil
shutil.rmtree(path)
Vedi the documentation per i dettagli di come gestire e/o ignorare gli errori.
Volete shutil.rmtree
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.
La libreria standard comprende shutil.rmtree per questo. Per impostazione predefinita,
shutil.rmtree(path) # errors if dir not empty
darà OSError: [Errno 66] Directory not empty: <your/path>
.
È possibile eliminare la directory e il suo contenuto in ogni caso ignorando l'errore:
shutil.rmtree(role_fs_path, ignore_errors=True)
È possibile eseguire più sofisticata gestione degli errori da parte anche di passaggio onerrror=<some function(function, path, excinfo)>
.
Questo non funziona se ci sono file nella directory. Guarda il post di dghubble. – CornSmith