Python ファイルが存在(チェック)するか確認する方法(2種類)

Python

確認ファイル構造

確認プログラムは【views.py】に記載

views.pyと同階層に「test」フォルダ、そのtestフォルダ配下に「test.txt」を配置

os.path.exists

https://docs.python.org/ja/3/library/os.path.html?highlight=os path exists#os.path.exists

ファイル(又はフォルダ)の存在を確認する

構文
os.path.exists(path)

ファイルの場合

import os

text_dir = os.path.dirname(__file__)
test_file = os.path.join(text_dir, 'text', 'test.txt')

if os.path.exists(test_file):
    print("存在します")
else:
    print("存在しません")

-- 結果 --
存在します

フォルダの場合

pathにフォルダパスを入れる

import os

text_dir = os.path.dirname(__file__)
test_file = os.path.join(text_dir, 'text')

if os.path.exists(test_file):
    print("存在します")
else:
    print("存在しません")

-- 結果 --
存在します

os.path.isfile

https://docs.python.org/ja/3/library/os.path.html?highlight=isfile#os.path.isfile

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

構文
os.path.isfile(path)
【views.py】

import os

text_dir = os.path.dirname(__file__)
test_file = os.path.join(text_dir, 'text', 'test.txt')

if os.path.isfile(test_file):
    print("存在します")
else:
    print("存在しません")

-- 結果 --
存在します

【isfile】でフォルダを指定した場合

システムエラーとはならず “False” となる

【views.py】

import os

text_dir = os.path.dirname(__file__)
test_file = os.path.join(text_dir, 'text')

if os.path.isfile(test_file):
    print("存在します")
else:
    print("存在しません")

-- 結果 --
存在しません

プロフィール背景画像 プロフィール画像
名前:田中寛之
今まで約20年間、出版社、マスコミ、化粧品会社、システム会社・病院・クリニックにてシステムエンジニアとして勤務。現在、個人事業主「ONLINE-WORLD」として活動し、42歳からPythonを始めました!
プロフィール背景画像 プロフィール画像
名前:田中寛之
今まで約20年間、出版社、マスコミ、化粧品会社、システム会社・病院・クリニックにてシステムエンジニアとして勤務。現在、個人事業主「ONLINE-WORLD」として活動し、42歳からPythonを始めました!