使用 os 模塊
-
判斷文件是否存在
os.path.isfile(path)
-
判斷目錄是否存在
os.path.isdir(path)
-
判斷路徑是否存在
# 使用 path 模塊 os.path.exists(path) # 使用 access() 方法 os.access(path, os.F_OK)
使用 open 函數和異常捕獲
如果直接用 open()
函數打開一個不存在的文件時,程序會拋出異常,我們可以通過 try 語句來捕獲異常以達到判斷文件是否存在的目的。
如果文件不存在,open() 函數會拋出 FileNotFoundError
異常。如果文件無操作權限,則會拋出 PersmissionError
異常。
filePath = '/path/to/file' try: file = open(filePath) file.close() except FileNotFoundError: print("No such file or directory: '%s'" % filePath) except IsADirectoryError: print("Is a directory: '%s'" % filePath) except PermissionError: print("Permission denied: '%s'" % filePath) else: print("File is exist: '%s'" % filePath)
使用 pathlib 模塊
import pathlib path = pathlib.Path('path/to/file') # 判斷路徑是否存在 path.exists() # 判斷是否為文件 path.is_file() # 判斷是否為目錄 path.is_dir()