Poista tiedosto tai kansio

Kuinka poistaa tiedosto tai kansio Pythonissa?

Ratkaisu

os.remove() poistaa tiedoston.

os.rmdir() poistaa tyhjän hakemiston.

shutil.rmtree() poistaa hakemiston ja sen koko sisällön.


Python 3.4+ -moduulin Pathlib Path objektit käyttävät myös näitä metodeja:

Kommentit (5)

Käytä

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

(Katso täydellinen dokumentaatio osoitteessa shutil) ja/tai

os.remove

ja

os.rmdir

(Täydellinen dokumentaatio os.)

Kommentit (1)

Luo toiminto teitä varten.

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))
Kommentit (2)