如何使用 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")
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP