Pythonでファイル、ディレクトリ(フォルダ)の存在確認

Modified: | Tags: Python, ファイル処理

Pythonでファイルやディレクトリ(フォルダ)が存在するかどうかを確認をするには、os.path.isfile(), os.path.isdir(), os.path.exists()を使う。パスをオブジェクトとして操作・処理するpathlibモジュールにも同様のメソッドがある。

ここでは例として以下の3つのパス文字列を使う。存在するファイルおよびディレクトリを示すパスと、存在しないパス。

import os

file_path = 'data/temp/dir/file.txt'
dir_path = 'data/temp/dir'
non_existent_path = 'non_exist'

なお、後述するが、ディレクトリのパスの末尾の区切り文字/はあってもなくてもよい。

パス文字列の操作については以下の記事を参照。

ファイルの存在確認: os.path.isfile()

ファイルの存在確認にはos.path.isfile()を使う。

指定したパスが存在するファイルであればTrueを返す。ディレクトリを示すパスの場合は存在していてもFalseを返す。

print(os.path.isfile(file_path))
# True

print(os.path.isfile(dir_path))
# False

print(os.path.isfile(non_existent_path))
# False

拡張子のないファイル名(Makefileなど)もファイルとして認識して正しく判定してくれる。

ディレクトリ(フォルダ)の存在確認: os.path.isdir()

ディレクトリ(フォルダ)の存在確認にはos.path.isdir()を使う。

指定したパスが存在するディレクトリであればTrueを返す。ファイルを示すパスの場合は存在していてもFalseを返す。

print(os.path.isdir(file_path))
# False

print(os.path.isdir(dir_path))
# True

print(os.path.isdir(non_existent_path))
# False

ファイル・ディレクトリ(フォルダ)の存在確認: os.path.exists()

パスが存在しているか(有効なパスか)を確認するにはos.path.exists()を使う。

ファイルでもディレクトリでも、存在していればTrue、存在していなければFalseを返す。

print(os.path.exists(file_path))
# True

print(os.path.exists(dir_path))
# True

print(os.path.exists(non_existent_path))
# False

ディレクトリ(フォルダ)のパス末尾の区切り文字の有無

これまでの例ではディレクトリのパスとして末尾の区切り文字/なしのものを使ってきたが、区切り文字がついていても同様の結果が返される。

ディレクトリのパス末尾の区切り文字の有無は気にしなくてよい。

dir_path_with_sep = 'data/temp/dir/'

print(os.path.exists(dir_path_with_sep))
# True

print(os.path.isfile(dir_path_with_sep))
# False

print(os.path.isdir(dir_path_with_sep))
# True

pathlibモジュールの場合: is_file(), is_dir(), exists()

パスをオブジェクトとして操作・処理するpathlibモジュールでも同様の判定が可能。pathlibの基本については以下の記事を参照。

以下のPathオブジェクトを例とする。

from pathlib import Path

p_file = Path('data/temp/dir/file.txt')
p_dir = Path('data/temp/dir')
p_non_existent = Path('non_exist')

Pathオブジェクトのis_file(), is_dir(), exists()メソッドを使う。

ファイルの存在確認はis_file()メソッド。

print(p_file.is_file())
# True

print(p_dir.is_file())
# False

print(p_non_existent.is_file())
# False

ディレクトリの存在確認はis_dir()メソッド。

print(p_file.is_dir())
# False

print(p_dir.is_dir())
# True

print(p_non_existent.is_dir())
# False

ファイル・ディレクトリを問わず、パスが存在しているかの確認はexists()メソッド。

print(p_file.exists())
# True

print(p_dir.exists())
# True

print(p_non_existent.exists())
# False

Pathオブジェクト生成時の末尾の区切り文字は無視されるので、あってもなくてもよい。

print(Path('data/temp/dir') == Path('data/temp/dir/'))
# True

関連カテゴリー

関連記事