Python os.unlink() Method

Python os.unlink() Method

  1. Syntax of os.unlink() Method
  2. Example 1: Use the os.unlink() Method to Remove or Delete a File Path
  3. Example 2: Handling Errors in the os.unlink() Method
  4. Example 3: Use Conditional Statements With the os.unlink() Method

Python os.unlink() method is an efficient way of removing a file path or directory. This method is syntactically similar to the os.remove() method.

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

Parameters

path It is an address object of a file system path or a symlink. The object can either be an str or bytes.
* The asterisk shows that all following parameters are keyword-only.
dir_fd It is an optional parameter representing a file descriptor referring to a path. Its default value is set as None.

Return

In the execution process, this method does not return any value.

import os

os.open( "File.txt", os.O_RDWR|os.O_CREAT )

path = "/home/File.txt"

os.unlink(path)

print("The file has been removed successfully.")

Output:

The file has been removed successfully.

An OSError might occur while using the os.unlink() method due to invalid or inaccessible processes and paths.

import os

path = '/home/User/File.txt'

try:
	os.unlink(path)

	print("The file path has been removed successfully.")

except IsADirectoryError:

	print("The given path is a directory, and it can't be removed with this method.")

except FileNotFoundError :

	print("No such file or directory has been found.")

except PermissionError:

	print("Access denied")

except :
	print("The file can not be deleted.")

Output:

No such file or directory has been found.

Note that the os.unlink() method cannot remove a directory. If the parameter entered is a directory, then the IsADirectoryError error is thrown.

Alternatively, the os.rmdir() method can be used to remove a valid path or directory.

import os

if(os.path.isfile("File.txt")):

        os.unlink("File.txt")

        print("The file has been deleted successfully.")

else:

    print("The file does not exist.")

Output:

The file does not exist.

Alternatively, you can use the os.remove method in the above code.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method