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