What is os.unlink() method in Python?

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 the os.rmdir() function.

Syntax

os.unlink(path, *, dir_fd=None)

Parameters

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.

Return value

It does not return any value.

Exception

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.

Explanation

Now, let's explain this method in detail with the help of a code example.

main.py
data.txt
# including OS module
import os
# creating a file path
path = os.path.abspath("data.txt")
# print path on console
print("File path: "+ path)
# Remove the file using os.unlink() method
os.unlink(path)
# message to user
print("File path was removed successfully")
  • Line 2: We import the OS module.
  • Line 4: We extract the absolute file path of data.txt.
  • Line 6: We print the file path on the console.
  • Line 8: We invoke os.unlink() to delete the file.
  • Line 10: We print a message to the console.

Free Resources