プログラムを書く際、時にはファイルやディレクトリが存在するかどうかを確認する必要があります。
Pythonでは、osモジュールのos.pathモジュールにいくつかの便利なメソッドが用意されています。
今回はその中から、os.path.isfile()
、os.path.isdir()
、os.path.exists()
メソッドについて見ていきます。
目次
1. os.path.isfile()
メソッド
os.path.isfile()
メソッドは、指定されたパスがファイルであるかどうかを判定します。
ファイルであればTrueを返し、それ以外の場合はFalseを返します。以下に使用例を示します。
import os
file_path = "sample.txt"
if os.path.isfile(file_path):
print(f"{file_path} exists and is a file.")
else:
print(f"{file_path} does not exist or is not a file.")
この例では、カレントディレクトリに"sample.txt"というファイルが存在する場合にその旨が表示されます。
2. os.path.isdir()
メソッド
os.path.isdir()
メソッドは、指定されたパスがディレクトリであるかどうかを判定します。
ディレクトリであればTrueを返し、それ以外の場合はFalseを返します。以下に使用例を示します。
import os
dir_path = "my_directory"
if os.path.isdir(dir_path):
print(f"{dir_path} exists and is a directory.")
else:
print(f"{dir_path} does not exist or is not a directory.")
この例では、カレントディレクトリに"my_directory"というディレクトリが存在する場合にその旨が表示されます。
3. os.path.exists()
メソッド
os.path.exists()
メソッドは、指定されたパスが存在するかどうかを判定します。
存在すればTrueを返し、存在しなければFalseを返します。以下に使用例を示します。
import os
path = "my_file_or_directory"
if os.path.exists(path):
print(f"{path} exists.")
else:
print(f"{path} does not exist.")
この例では、カレントディレクトリに"my_file_or_directory"というファイルまたはディレクトリが存在する場合にその旨が表示されます。
これらのメソッドを利用することで、Pythonで簡単にファイルやディレクトリの存在を確認することができます。プログラムを書く際に、事前に存在の確認を行うことで、安全性を向上させることができます。
以上が、Pythonでファイルやディレクトリの存在を確認する方法になります。