Pythonで、フォルダを再帰的に処理する方法は?

osモジュールのwalk()関数を使用すると、フォルダを再帰的に走査することができます。この関数は、すべてのファイルとサブフォルダを再帰的に走査するためのジェネレータを返します。

以下是一个示例代码,展示了如何使用递归方法遍历文件夹:

import os

def traverse_folder(folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            file_path = os.path.join(root, file)
            print(file_path)

# 调用函数遍历文件夹
traverse_folder('path/to/folder')

上記のコードでは、traverse_folder()関数がフォルダのパスを引数として受け取り、os.walk()関数を使用してそのフォルダを走査します。os.walk()関数は、ジェネレータを返します。各イテレーションで、(root, dirs, files)の3つ組を返します。ここで、rootは現在走査しているフォルダのパス、dirsはそのフォルダ内のサブフォルダのリスト、filesはそのフォルダ内のファイルのリストです。

while looping, we can get the full path of each file by using os.path.join(root, file), and then perform necessary operations, such as printing the file path.
ループ中に、os.path.join(root, file)を使用して各ファイルの完全なパスを取得し、ファイルパスを出力するなど、必要な操作を行うことができます。

bannerAds