Löschen einer Datei oder eines Ordners

Wie löscht man eine Datei oder einen Ordner in Python?

Lösung

os.remove() löscht eine Datei.

os.rmdir() löscht ein leeres Verzeichnis.

shutil.rmtree() löscht ein Verzeichnis und dessen gesamten Inhalt.


Path Objekte aus dem Python 3.4+ pathlib Modul stellen diese Instanzmethoden ebenfalls zur Verfügung:

Kommentare (5)

Verwenden Sie

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

(Siehe vollständige Dokumentation auf shutil) und/oder

os.remove

und

os.rmdir

(Vollständige Dokumentation auf os.)

Kommentare (1)

Erstellen Sie eine Funktion für Sie.

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))
Kommentare (2)