pythonでディレクトリ内のファイルをよみこむ方法

Pythonのosモジュールとglobモジュールを使用して、フォルダーのファイルを検索できます。よく使われる方法は次の2つです。

方法1: osモジュールのlistdir関数

import os

folder_path = '文件夹路径'
for filename in os.listdir(folder_path):
    file_path = os.path.join(folder_path, filename)
    if os.path.isfile(file_path):
        with open(file_path, 'r') as file:
            # 处理文件内容
            pass

方法 2: glob モジュールの glob 関数を使う

import glob

folder_path = '文件夹路径'
file_list = glob.glob(folder_path + '/*')
for file_path in file_list:
    if os.path.isfile(file_path):
        with open(file_path, 'r') as file:
            # 处理文件内容
            pass

上記のコードでは、「’フォルダパス’」を実際のフォルダパスに置き換える必要があります。その後、ファイル内のファイルを繰り返し処理し、open 関数を使用してファイルを開いて処理します。

bannerAds