# Python Delete File and Folder With os and shutil

> Remove files with os.remove(), empty directories with os.rmdir(), and non-empty directories with shutil.rmtree(), plus existence checks to prevent errors

**URL:** https://sentry.io/answers/delete-a-file-or-folder-in-python/

---

## The Problem

How do I delete a file or folder in Python?

## The Solution

We can use functions from Python's built-in `os` module to delete files and empty folders.

* [`os.remove()`](https://docs.python.org/3/library/os.html#os.remove) will delete a file.
* [`os.rmdir()`](https://docs.python.org/3/library/os.html#os.rmdir) will delete an empty folder.

To delete a folder that is not empty, we must use the [`rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree) function from Python's `shutil` module.

For example:

```python
import os, shutil

os.remove("unwanted-file.txt")
os.rmdir("empty-dir")
shutil.rmtree("nonempty-dir")
```

Note that these functions will throw errors if the file or directory to be deleted does not exist. We can avoid this by using [`os.path.isfile()`](https://docs.python.org/3/library/os.path.html#os.path.isfile) and [`os.path.isdir()`](https://docs.python.org/3/library/os.path.html#os.path.isdir) to test for their existence before attempting the deletion:

```python
import os, shutil

if os.path.isfile("unwanted-file.txt"):
    os.remove("unwanted-file.txt")

if os.path.isdir("empty-dir"):
    os.rmdir("empty-dir")

if os.path.isdir("nonempty-dir"):
    shutil.rmtree("nonempty-dir")
```

## Further Reading

If you're looking to get a deeper understanding of how Python application monitoring works, take a look at the following articles:

- [Logging in Python: A Developer's Guide](https://blog.sentry.io/logging-in-python-a-developers-guide/)
- [Application Performance Monitoring Explained](https://sentry.io/resources/application-performance-monitoring-explained/)
- [Python: Set Up Tracing](https://docs.sentry.io/platforms/python/tracing/)
- [Sentry for Python](https://docs.sentry.io/platforms/python/)
- [Python Error and Performance Monitoring](https://sentry.io/for/python/)
- [11 Habits of Highly Effective Developers](https://syntax.fm/show/778/11-habits-of-highly-effective-developers)

---

*Source: [sentry.io/answers/delete-a-file-or-folder-in-python/](https://sentry.io/answers/delete-a-file-or-folder-in-python/)*
