Python 判斷文件/目錄是否存在


使用 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()

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM