How to delete a file or folder using Python?
Removing files
Remove a file with os.remove()
1
2
3
| import os
os.remove("path/to/file")
|
Remove a file with pathlib.Path.unlink()
1
2
3
4
| from pathlib import Path
p = Path("path/to/file")
p.unlink()
|
Removing directories
Remove an empty directory with os.rmdir()
1
2
3
| import os
os.rmdir("path/to/folder")
|
Remove an empty directory with pathlib.Path.rmdir()
1
2
3
4
| from pathlib import Path
p = Path("path/to/folder")
p.rmdir()
|
Remove an empty directory and its contents with shutil.rmtree()
1
2
3
| import shutil
shutil.rmtree("path/to/folder")
|