Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

unlink
os module
python programming

What is os.unlink() method in Python?

Salman Yousaf

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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")
Implementing the os.unlink method
  • 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.

RELATED TAGS

unlink
os module
python programming

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring