Pythonのosモジュールを使うと、ファイルの存在を確認することができます。os.path.exists関数は、ファイルが存在する場合はTrueを、存在しない場合はFalseを返します。以下はその例です。
1 2 3 4 5 6 7 8 | import os file_path = "path/to/file.txt" if os.path.exists(file_path): print(f"The file {file_path} exists.") else: print(f"The file {file_path} does not exist.") |
また、os.path.isfile 関数を使用して、ファイルが存在し、かつファイルであるかどうか(ディレクトリやシンボリックリンクなどではない)を確認することができます。
1 2 3 4 5 6 7 8 | import os file_path = "path/to/file.txt" if os.path.isfile(file_path): print(f"{file_path} is a file.") else: print(f"{file_path} is not a file.") |