Kuinka poistaa tiedosto tai kansio Pythonissa?
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:
`pathlib.Path.unlink()
poistaa tiedoston tai symbolisen linkin.
`pathlib.Path.rmdir()
poistaa tyhjän hakemiston.
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.)
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))