Python os.unlink() 方法



Python 的 OS 模組的 unlink() 方法用於移除(刪除)單個檔案路徑。如果路徑是一個目錄,則會引發 OSError 異常。

當我們需要從系統中刪除臨時檔案或不必要的檔案時,可以使用此方法。請務必記住,os.unlink() 只能刪除檔案,不能刪除目錄。

語法

以下是 os.unlink() 方法的語法:

os.unlink(path, *, dir_fd)

引數

Python 的 os.unlink() 方法接受兩個引數,如下所示:

  • 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','tutorialsdir','amrood.admin' ]
The dir after removal of path : 
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','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}")

執行上述程式時,由於系統中不存在 "newFile.txt",因此會引發 "FileNotFoundError" 異常。

file not found
python_files_io.htm
廣告
© . All rights reserved.