How do I delete a file or folder in Python?

Better Stack Team
Updated on January 26, 2023

You can use the os module to delete a file or folder in Python.

To delete a file, you can use the os.remove() function. This function takes the file path as an argument and deletes the file at that path.

 
import os

# Delete the file at the specified path
os.remove("/path/to/file.txt")

To delete a folder, you can use the os.rmdir() function. This function takes the folder path as an argument and deletes the folder at that path. Note that the folder must be empty in order for this function to work.

 
import os

# Delete the folder at the specified path
os.rmdir("/path/to/folder")

If you want to delete a folder and all of its contents, you can use the shutil module's rmtree() function. This function takes the folder path as an argument and deletes the folder and all of its contents, including any subfolders and files.

 
import shutil

# Delete the folder and all of its contents
shutil.rmtree("/path/to/folder")
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →