如何使用Python檢查檔案是否存在?
您可能希望僅當檔案或目錄存在或不存在時才在 Python 指令碼中執行特定操作。例如,您可能希望從配置檔案讀取或寫入配置檔案,或者僅在檔案不存在時才建立檔案。
在 Python 中,有很多不同的方法來檢查檔案是否存在並確定它是什麼型別的檔案。
使用 OS 模組
一個名為 Os 的內建 Python 模組具有用於處理作業系統的工具。我們可以使用 os 來訪問作業系統功能。在 Python 中,os.path 是 os 的子模組。這用於更改通用路徑的名稱。
根據檔案是否存在,os.path 的兩種方法 isfile() 和 exists() 提供“True”或“False”值。
os.path.isfile() 方法
此方法確定指定路徑是否已經包含常規檔案。
語法
os.path.isfile(filepath)
其中,filepath 表示檔案的路徑。
返回型別取決於檔案是否存在,“True”或“False”。
示例
以下是一個使用 os.path.isfile() 方法檢查檔案是否存在或不存在的示例:
import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.isfile(filepath) print (doesFileExists)
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
True
os.path.exists() 方法
此方法檢查給定路徑是否存在。
語法
os.path.exists(filepath)
其中,filepath 表示檔案的路徑。
返回型別取決於檔案是否存在,“True”或“False”。
示例
以下是一個使用 os.path.exists() 方法檢查檔案是否存在或不存在的示例:
import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.exists(filepath) print(doesFileExists)
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
True
使用 pathlib 模組
一個名為 Pathlib 的內建面向物件的 Python 介面提供了一個用於處理檔案和目錄的物件 API。pathlib 模組提供了兩個用於確定檔案是否存在的方法,類似於 os 模組。
示例 - pathlib.path.exists() 方法
以下是一個使用 pathlib.path.exists() 方法檢查檔案是否存在或不存在的示例:
import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trials.py") if filepath.exists(): print ("The given file exists") else: print ("The given file does not exists")
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
The given file does not exists
示例 - pathlib.is_file() 方法
以下是一個使用 pathlib.is_file() 方法檢查檔案是否存在或不存在的示例:
import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trial.py") if filepath.is_file(): print ("The given file exists") else: print ("The given file does not exists")
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
The given file exists
使用 glob 模組
使用萬用字元字元,glob 模組用於查詢檔名符合特定模式的檔案。這也提供“True”或“False”值來指示檔案是否存在。
示例
以下是一個使用 glob 模組檢查檔案是否存在或不存在的示例:
import glob if glob.glob(r"C:\Users\Lenovo\Downloads\Work TP\trial.py"): print ("The given file exists") else: print("The given file does not exists")
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
The given file exists
異常處理方法
在 try 和 except 語句中,我們在“try”下編寫程式碼,“except”語句檢查“try”下程式碼的錯誤。“except”塊會在發現任何錯誤時執行。因此,我們使用“try”語句開啟檔案並確定它是否存在。如果檔案丟失,則會引發 IOError 異常,這允許我們列印輸出並顯示檔案丟失。
使用“test -e”,第一步是確認檔案的路徑有效。如果路徑有效,則我們使用“test -f”或“test -d”來確定檔案是否存在。
示例 - 1
以下是一個使用異常處理方法(**IOError**)檢查檔案是否存在或不存在的示例:
try: file = open('C:\Users\Lenovo\Downloads\Work TP\trial.py') print("The given file exists") file.close() except IOError: print("The given file does not exists")
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出:
The given file exists
示例 - 2
以下是一個使用異常處理方法(**FileNotFoundError**)檢查檔案是否存在或不存在的示例:
try: file = open('C:\Users\Lenovo\Downloads\Work TP\trials.py') print("The given file exists") file.close() except FileNotFoundError: print("The given file does not exists")
輸出
以下是根據檔案是否存在而生成的上述程式碼的輸出。
The given file does not exists