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