如何使用 Python 檢查檔案是否存在?


計算機中是否存在某個檔案可透過使用 Python 程式碼兩種方式驗證。一種方法是使用 os.path 模組的 isfile() 函式。如果指定路徑處存在檔案,該函式返回 true,否則返回 false。

>>> import os
>>> os.path.isfile("d:\Package1\package1\fibo.py")
True
>>> os.path.isfile("d:/Package1/package1/fibo.py")
True
>>> os.path.isfile("d:\nonexisting.txt")

請注意,在路徑中使用反斜槓時,必須使用兩個反斜槓來跳出 Python 字串。

另一種方法是捕獲 open() 函式在字串引數對應於不存在的檔案時引發的 IOError 異常。

try:
   fo = open("d:\nonexisting.txt","r")
   #process after opening file
   pass
   #
   fo.close()
except IOError:
   print ("File doesn't exist")

更新於:2019 年 7 月 30 日

570 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.