Python OS 模块的 unlink()方法删除(deletes)单个文件路径。如果路径是目录,则引发 OSError。
当我们需要从系统中删除临时或不必要的文件时,会使用此方法。永远记住 os.unlink() 只能删除文件,不能删除目录。
语法
以下是 os.unlink() 方法的语法 -
os.unlink(path, *, dir_fd)
参数
Python os.unlink() 方法接受下面列出的两个参数 -
- path − 这是要删除的 path。
- dir_fd − 这是一个可选参数,允许我们指定引用目录的文件描述符。
返回值
Python os.unlink() 方法不返回任何值。
例在以下示例中,我们将使用 unlink() 方法删除名为 “aa.txt” 的文件。
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()))
当我们运行上述程序时,它会产生以下结果——
The dir is:
[ 'a1.txt','aa.txt','resume.doc','a3.py','qikepudir','amrood.admin' ]
The dir after removal of path :
[ 'a1.txt','resume.doc','a3.py','qikepudir','amrood.admin' ]
[ 'a1.txt','aa.txt','resume.doc','a3.py','qikepudir','amrood.admin' ]
The dir after removal of path :
[ 'a1.txt','resume.doc','a3.py','qikepudir','amrood.admin' ]
例
由于 os.unlink() 方法与异常相关联,因此,有必要使用 try-except 块处理它们。
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}")
在运行上述程序时,它将引发 “FileNotFoundError”,因为 “newFile.txt” 在我们的系统中不可用。
file not found