[解決!Python]os.pathモジュールのisdir/isfile関数を使ってパスがディレクトリやファイルであるかどうかを調べるには解決!Python

あるパスがディレクトリかどうかや、ファイルかどうかを調べるにはos.pathモジュールのisdir/isfile関数が使える。その使い方や、os.scandir関数と組み合わせて使う方法を紹介する。

» 2022年10月11日 05時00分 公開
[かわさきしんじDeep Insider編集部]

この記事は会員限定です。会員登録(無料)すると全てご覧いただけます。

「解決!Python」のインデックス

連載目次

import os
from os.path import isdir, isfile, exists

# テスト用にディレクトリとファイルを作成
d = 'mydir'
if not exists(d):
    os.mkdir(d)

f = 'myfile.txt'
with open(f, 'wt'):
    pass

if isdir(d):
    print(f'{d} is a directory')
else:
    print(f'{d} is not a directory')
# 出力結果:
#mydir is a directory

if isfile(f):
    print(f'{f} is a file')
else:
    print(f'{f} is not a file')
# 出力結果:
#myfile.txt is a file

# os.scandir関数でカレントディレクトリにあるエントリを反復
for entry in os.scandir():
    if isdir(entry):
        print(f'{entry.name} is a directory')
    elif isfile(entry):
        print(f'{entry.name} is a file')
    else:
        print(f'{entry.name} is not a directory nor file')
# 出力結果:
#test.py is a file
#myfile.txt is a file
#mydir is a directory

# isdir/isfile関数を使わずにDirEntryクラスのメソッドを使える
for entry in os.scandir():
    if entry.is_dir():
        print(f'{entry.name} is a directory')
    elif entry.is_file():
        print(f'{entry.name} is a file')
    else:
        print(f'{entry.name} is not a directory nor file')
# 出力結果は上と同じ

# os.listdir関数の場合はisdir/isfile関数を使う
for path in os.listdir():
    if isdir(path):
        print(f'{path} is a directory')
    elif isfile(path):
        print(f'{path} is a file')
    else:
        print(f'{path} is not a directory nor file')
# 出力結果は上と同じ


os.pathモジュールのisdir/isfile関数

 os.pathモジュールにはisdir関数とisfile関数があり、これらを使うことで、引数に指定したパスがディレクトリかどうかや、ファイルかどうかを確認できる。

 ここではまずosモジュール、os.pathモジュールを使ってテスト用のディレクトリとファイルを作成しておこう。

import os
from os.path import exists

# テスト用にディレクトリとファイルを作成
d = 'mydir'
if not exists(d):
    os.mkdir(d)

f = 'myfile.txt'
with open(f, 'wt'):
    pass


 ここではmydirディレクトリとmyfile.txtファイルを作成している。

 os.mkdir関数は指定されたディレクトリが既に存在している場合、FileExistsError例外を発生するので、ここではos.path.exists関数でファイルの存在確認を行うようにしている。pathlibモジュールのPath.mkdirインスタンスメソッドではexist_ok引数にTrueを指定することで例外の発生を抑止できるが、os.mkdir関数ではそうはいかないことは覚えておこう。

 isdir関数は引数に指定されたパス(文字列、os.DirEntryクラスのインスタンス、Pathクラスのインスタンス)がディレクトリを指していればTrueを、そうでなければFalseを返す。

 パス「mydir」がディレクトリかどうかを示す例を以下に示す。

from os.path import isdir, isfile

# パスがディレクトリかどうかを調べる
if isdir(d):
    print(f'{d} is a directory')
else:
    print(f'{d} is not a directory')
# 出力結果:
#mydir is a directory


 ここではディレクトリ作成時に使用した文字列をisdir関数に渡しているので、その結果はTrueとなり「mydir is a directory」と表示される。

 isfile関数も同様に、引数に指定されたパス(文字列、os.DirEntryクラスのインスタンス、Pathクラスのインスタンス)がファイルを指していればTrueを、そうでなければFalseを返す。

 以下に例を示す。ここでもファイルの作成に使った文字列をisfile関数に渡しているので、その結果はTrueとなる。

if isfile(f):
    print(f'{f} is a file')
else:
    print(f'{f} is not a file')
# 出力結果:
#myfile.txt is a file


Copyright© Digital Advantage Corp. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。