Python os.unlink() Method
os.unlink() Overview
The os.unlink() method is used to delete a file, and returns an error if the file is a directory.
os.unlink() Syntax
The syntax format of the unlink() method is as follows.
os.unlink(path)
os.unlink() Parameters
- path – the path to the deleted file
os.unlink() Return Value
This method has no return value.
os.unlink() Example#1
The following example demonstrates the use of the unlink() method.
import os
path = "/root/apidemos.com.txt"
os.unlink(path)
print(path, "has been removed successfully!!!")
Output:
os.unlink() Example#2
if the given path is a directory then IsADirectoryError
exception will raised.
Similarly, if the specified file path does not exists or is invalid then corresponding OSError
will be raised.
import os
path = "/root/aaa-apidemos"
os.unlink(path)
print(path, " has been removed successfully")
Output:
os.unlink() Example#3
Try Removing the given file path using try and except block.
- If the given path is a directory,
IsADirectoryError
error will be raised. - If path is invalid or does not exists,
FileNotFoundError
error will be raised. - If the process has not the permission to remove the given file path,
PermissionError
error will raised.
import os
path = '/root/apidemos.com.txt'
try:
os.unlink(path)
print("File path removed successfully!!!")
except IsADirectoryError:
print("The given path is a directory!!!")
except FileNotFoundError :
print("No such file or directory found: ", path)
except PermissionError:
print("Permission denied!!!")
except :
print(path, "can not be removed")
Output: