Python has a few built-in modules that allow you to delete files and directories.
This tutorial explains how to delete files and directories using functions from the os
, pathlib
, and shutil
modules.
In Python you can use os.remove()
, os.unlink()
, pathlib.Path.unlink()
to delete a single file.
The [os](https://docs.python.org/3/library/os.html)
module provides a portable way of interacting with the operating system. The module is available for both Python 2 and 3.
To delete a single file with os.remove()
, pass the path to the file as an argument:
import os
file_path = '/tmp/file.txt'
os.remove(file_path)
Copy
os.remove()
and os.unlink()
functions are semantically identical:
import os
file_path = '/tmp/file.txt'
os.unlink(file_path)
Copy
If the specified file doesn’t exist a FileNotFoundError
error is thrown. Both os.remove()
and os.unlink()
can delete only files, not directories. If the given path points to a directory, they will trow IsADirectoryError
error.
#python