how.wtf

How to delete files and directories in Python

· Thomas Taylor

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")
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")

#python  

Reply to this post by email ↪