Pythonで指定したファイル名や拡張子のファイルを検索する方法

Pythonで指定したファイル名や拡張子のファイルを検索するには、osモジュールやos.walk()関数、globモジュール、pathlibモジュールなどを使用する方法があります。以下にそれぞれの方法を示します。

1. osモジュールとos.walk()関数を使用する方法 (ファイル名の検索):

python
import os

# 検索を開始するディレクトリのパスを指定
search_directory = "/path/to/your/directory"

# 検索対象のファイル名を指定
target_file_name = "target_file.txt"

# ファイル名が一致するファイルを検索
found_files = []
for root, dirs, files in os.walk(search_directory):
    for file in files:
        if file == target_file_name:
            found_files.append(os.path.join(root, file))

print("検索結果:")
for file_path in found_files:
    print(file_path)

この方法では、os.walk()関数を使用して指定したディレクトリ以下のすべてのファイルを再帰的に走査し、検索したいファイル名と一致するものを取得します。

2. globモジュールを使用する方法 (拡張子の検索):

python
import glob

# 検索対象の拡張子を指定
target_extension = "*.txt"

# 検索を開始するディレクトリのパスを指定
search_directory = "/path/to/your/directory"

# 指定した拡張子に一致するファイルを検索
found_files = glob.glob(os.path.join(search_directory, target_extension))

print("検索結果:")
for file_path in found_files:
    print(file_path)

glob.glob()関数を使用して、指定したディレクトリ内で指定した拡張子に一致するファイルを取得します。

3. pathlibモジュールを使用する方法 (ファイル名の検索):

python
from pathlib import Path

# 検索を開始するディレクトリのパスを指定
search_directory = Path("/path/to/your/directory")

# 検索対象のファイル名を指定
target_file_name = "target_file.txt"

# ファイル名が一致するファイルを検索
found_files = list(search_directory.glob(f"**/{target_file_name}"))

print("検索結果:")
for file_path in found_files:
    print(file_path)

pathlib.Path().glob()メソッドを使用して、指定したディレクトリ以下でファイル名が一致するファイルを取得します。

どの方法も、指定した条件に一致するファイルを検索できます。選択肢のどれかを選んで使用することができます。