Python os.unlink() Method
Python method unlink() of OS module removes (deletes) a single file path. If the path is a directory, OSError is raised.
This method is used when we need to delete temporary or unnecessary files from the system. Always remember os.unlink() can only delete files, not directories.
Syntax
Following is the syntax for os.unlink() method −
os.unlink(path, *, dir_fd)
Parameters
The Python os.unlink() method accepts two parameters which are listed below −
path − This is the path, which is to be removed.
dir_fd − This is an optional parameter that allows us to specify a file descriptor referring to a directory.
Return Value
The Python os.unlink() method does not return any value.
Example
In the following example, we are removing a file named "aa.txt" using the unlink() method.
import os, sys
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.unlink("aa.txt")
# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))
When we run above program, it produces following result −
The dir is: [ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ] The dir after removal of path : [ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
Example
Since the os.unlink() method is associated with exceptions, hence, it is necessary to handle them using try-except block.
import os
# path of file
pathofFile = "/home/tp/Python/newFile.txt"
# to handle errors
try:
os.unlink(pathofFile)
print("deletion successfull")
except FileNotFoundError:
print("file not found")
except PermissionError:
print("Permission denied")
except Exception as err:
print(f"error occurred: {err}")
On running the above program, it will raise "FileNotFoundError" as "newFile.txt" is not available in our system.
file not found