Kā dzēst failu vai mapi Python programmā?
os.remove()
noņem failu.
os.rmdir()
2 noņem tukšu direktoriju.
shutil.rmtree()
dzēš direktoriju un visu tā saturu.
Path
objekti no Python 3.4+ pathlib
moduļa arī piedāvā šīs instances metodes:
pathlib.Path.unlink()
pathlib.Path.unlink()
dzēš failu vai simbolisko saiti.
pathlib.Path.rmdir()
dzēš tukšu direktoriju.
Izmantojiet
shutil.rmtree(path[, ignore_errors[, onerror]])
(Skatīt pilnu dokumentāciju shutil) un/vai
os.remove
un
os.rmdir
(Pilna dokumentācija atrodama os.)
Izveidojiet funkciju, kas paredzēta jums.
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))