[解決!Python]os.pathモジュールのexists関数を使ってパスが存在するかどうかを確認するには解決!Python

exists関数に渡したパスが実際に存在するかどうかを確認したり、isdir/isfile関数と組み合わせて処理を振り分けたりする方法を紹介する。

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

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

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

連載目次

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

mydir = 'mydir'
myfile = 'myfile.txt'
nofile_or_dir = 'nofile_or_dir'

# mydirディレクトリとmyfile.txtファイルを作成
os.mkdir(mydir)

with open(myfile, 'w'):
    pass

print(exists(mydir))  # True
print(exists(myfile))  # True
print(exists(nofile_or_dir))  # False

# ディレクトリが存在しなければ作成する
if not exists(mydir):
    os.mkdir(mydir)
else:
    print(f'{mydir} already exists')

# ファイルが存在していればバックアップを取り、書き込みを行う
if exists(myfile):
    newfile = splitext(myfile)[0] + '.bak'
    os.rename(myfile, newfile)

with open(myfile, 'w') as f:
    f.write('some text')

# 指定されたファイル/ディレクトリの存在確認の後、処理を振り分ける
def do_some_work(path):
    if not exists(path):
        res = input(f'{path} not exists. create it? (y/n)')
        if res == 'y':
            with open(path, 'w'):
                pass

    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')

paths = [mydir, myfile, nofile_or_dir]
for path in paths:
    do_some_work(path)


os.pathモジュールのexists関数

 os.pathモジュールのexists関数は引数に指定したパス(文字列またはpathlibモジュールで定義されるPathクラスのインスタンスなど)が実際に存在するディレクトリやファイルを指しているかどうかを調べるのに使える。パスが存在していればTrueが、そうでなければFalseが返される。

 以下に例を示す。

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

mydir = 'mydir'
myfile = 'myfile.txt'
nofile_or_dir = 'nofile_or_dir'

# mydirディレクトリとmyfile.txtファイルを作成
os.mkdir(mydir)

with open(myfile, 'w'):
    pass

print(exists(mydir))  # True
print(exists(myfile))  # True
print(exists(nofile_or_dir))  # False


 このコードではまずmydirディレクトリをosモジュールのmkdir関数を使って作成し、その後、myfile.txtファイルを作成している。変数nofile_or_dirの値である「nofile_or_dir」という名前のファイルやディレクトリは存在していない。なお、os.pthモジュールを使用したディレクトリの作成については「ディレクトリを作成/削除するには:osモジュール編」を、open関数を使ったファイルの作成については「ファイルを作成/削除するには」を参照されたい。

 最後の3行ではexists関数を使って3つのパス(mydir、mydir.txt、nofile_or_dir)についてディレクトリやファイルが存在しているかを試している。最初の2つについてはその上で作成しているのでTrueが、最後のnofile_or_dirについてはそのような名前のディレクトリもファイルもないのでFalseが返されている。

Copyright© Digital Advantage Corp. All Rights Reserved.

RSSについて

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

メールマガジン登録

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