The OS module provides various functions that allow the user to interact with the operating system when using Python. os.unlink()
is one of them.
The os.unlink()
method is used to delete or remove a file path in Python. It is similar to the os.remove()
function. Both these methods are used to delete or remove a file path. Moreover, os.remove()
and os.unlink()
methods cannot remove or delete a directory.
To delete a directory, one can use theos.rmdir()
function.
os.unlink(path, *, dir_fd=None)
It takes the following argument values:
path
: This is the path of file that is to be deleted. It is a path-like instance, either a string or a bytes object.*
: This indicates that all following arguments—in this case, dir_fd
—are keyword arguments, not positional arguments.dir_fd
(optional): This is a file descriptor that refers to a directory. It defaults to None
.It does not return any value.
It also throws the following exceptions:
IsADirectoryError
: It throws a directory error when the argument path is a directory, not a file path.OSError
: It throws this exception when the specified path is inaccessible.Now, let's explain this method in detail with the help of a code example.
# including OS moduleimport os# creating a file pathpath = os.path.abspath("data.txt")# print path on consoleprint("File path: "+ path)# Remove the file using os.unlink() methodos.unlink(path)# message to userprint("File path was removed successfully")
data.txt
.os.unlink()
to delete the file.