如何使用 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-07-30

571 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.