Skip to content

How can I delete a file or folder in Python?

To delete a file or folder in Python, you can use the os module and call the os.remove() function to delete a file, or the shutil.rmtree() function to delete a folder and all its contents. Here is an example of how to use these functions:

Delete a file or a folder in Python

python
import os
import shutil

# Delete a file
os.remove("path/to/file.txt")

# Delete a folder and all its contents
shutil.rmtree("path/to/folder")

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

Note that these functions will raise an error if the file or folder does not exist, so you may want to include some error handling to catch this case.

Handle exceptions while you try to remove a file or a folder in Python

python
import os
import shutil

# Delete a file
try:
    os.remove("path/to/file.txt")
except FileNotFoundError:
    print("File not found")

# Delete a folder and all its contents
try:
    shutil.rmtree("path/to/folder")
except FileNotFoundError:
    print("Folder not found")

Dual-run preview — compare with live Symfony routes.