Python にファイルが存在するかどうかを確認する方法
-
try...except
でファイルの存在を確認する(> Python 2.x) -
ファイルが存在するかどうかを確認するための
os.path.isfile()
(> = Python 2.x) -
ファイルが存在するかどうかを確認するための
pathlib.Path.is_file()
(> = Python 3.4)

このチュートリアルでは、Python にファイルが存在するかどうかを確認する 3つの異なるソリューションを紹介します。
- ファイルの存在を確認するための
try...except
ブロック(> = Python 2.x) - ファイルの存在を確認する
os.path.isfile
関数(> = Python 2.x) pathlib.Path.is_file()
ファイルの存在を確認します(> = Python 3.4)
try...except
でファイルの存在を確認する(> Python 2.x)
ファイルを開こうとして、IOError
(Python 2.x)または FileNotFoundError
(Python 3.x)がスローされるかどうかに応じて、ファイルが存在するかどうかを確認できます。
def checkFileExistance(filePath):
try:
with open(filePath, 'r') as f:
return True
except FileNotFoundError as e:
return False
except IOError as e:
return False
上記のコード例では、例外キャッチ部分に FileNotFoundError
と IOError
の両方をリストすることで、Python 2/3 と互換性を持たせています。
ファイルが存在するかどうかを確認するための os.path.isfile()
(> = Python 2.x)
import os
fileName = r"C:\Test\test.txt"
os.path.isfile(fileName)
ファイル fileName
が存在するかどうかをチェックします。
一部の開発者は、os.path.exists()
を使用してファイルが存在するかどうかを確認することを好みます。しかし、オブジェクトがファイルかディレクトリかを区別できませんでした。
import os
fileName = r"C:\Test\test.txt"
os.path.exists(fileName)
#Out: True
fileName = r"C:\Test"
os.path.exists(fileName)
#Out: True
したがって、ファイルが存在するかどうかを確認したい場合にのみ os.path.isfile
を使用してください。
ファイルが存在するかどうかを確認するための pathlib.Path.is_file()
(> = Python 3.4)
Python 3.4 以降、pathlib
モジュールにオブジェクト指向メソッドを導入して、ファイルが存在するかどうかを確認します。
from pathlib import Path
fileName = r"C:\Test\test.txt"
fileObj = Path(fileName)
fileObj.is_file()
同様に、ディレクトリまたはファイル/ディレクトリが存在するかどうかを確認するための is_dir()
および exists()
メソッドもあります。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn