Python - フォルダ(ディレクトリ)の存在確認方法

フォルダの有無をチェックするには、os.path.isdir()関数を使用します。

フォルダ(ディレクトリ)があるか、確認する方法

os.path.isdir()メソッドの引数に確認したいファイルのパスを渡します。フォルダがあれば True を返し、それ以外は False を返します。

os.path.isdir の使用方法

import os

結果(True or False) = os.path.isdir('ファイルパス')

サンプルコード1

次のサンプルコードは、フォルダ「test-dir」があるか確認しています。
import os

# ディレクトリがあるか判定
filePath = './test-dir'
result = os.path.isdir(filePath)
if result:
    print(f'ディレクトリ{filePath}は存在します。')
else:
    print(f'ディレクトリ{filePath}は存在しません。')

サンプルコード2

フォルダ(ディレクトリ)やショートカット(Windows)の有無を確認しようとしています。
import os

# ディレクトリがある場合、True を返す
filePath = './test-dir'
result = os.path.isdir(filePath)
if result:
    print(f'ディレクトリ{filePath}は存在します。')
else:
    print(f'ディレクトリ{filePath}は存在しません。')

# ファイルの場合は存在していても False を返す
filePath = './test.txt'
result = os.path.isdir(filePath)
if result:
    print(f'ディレクトリ{filePath}は存在します。')
else:
    print(f'ディレクトリ{filePath}は存在しません。')

# ショートカット(Windows)の場合は False を返す
filePath = './test-dir - ショートカット'
result = os.path.isdir(filePath)
if result:
    print(f'ディレクトリ{filePath}は存在します。')
else:
    print(f'ディレクトリ{filePath}は存在しません。')

テスト用のファイル
テスト用のファイル
サンプルコードの実行結果
サンプルコードの実行結果

検証環境