Python でファイルの存在確認をする

Python でファイルが存在するか確認する方法

os.path.isfile()関数にパス名を渡すと、そのパスが存在して、ファイルである場合に True を返します。

import os
path = 'foo.txt'
is_file = os.path.isfile(path)
if is_file:
    print(f"{path} is a file.")
else:
    pass # パスが存在しないかファイルではない

Python でディレクトリが存在するか確認する方法

import os
path = 'venv'
is_dir = os.path.isdir(path)
if is_dir:
    print(f"{path} is a directory.")
else:
    pass # パスが存在しないかディレクトリではない

Python でパスが存在するか確認する方法

os.path.exists() を使うと、引数に指定したパスが存在するか確認できます。

import os
r = os.path.exists('foo.txt')
print(r) # True (存在する)

この例では、 os.path.exists() 関数には、絶対パスではなくファイル名しか渡していません。 この場合は、現在のディレクトリ内からのパスを探します。

os.path.exists() の結果だけでは、そのパスがファイルであるかディレクトリであるかはわかりません。 上で説明したの os.path.isfile()os.path.isdir() を用いてファイルであるかディレクトリであるかなどを判定できます。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

シェア数
facebook sharing button シェアする
twitter sharing button ツイートする
pinterest sharing button ピン
email sharing button Eメール
sharethis sharing button シェアする
© 2023 Python 入門