Python Loop Through Folders: os.walk Tutorial

In Python, you can use the os module to loop through folders. Below is an example code that demonstrates how to loop through all files and subfolders in a folder.

import os

# 指定要遍历的文件夹路径
folder_path = 'path_to_folder'

# 遍历文件夹中的所有文件和子文件夹
for root, dirs, files in os.walk(folder_path):
    for file in files:
        # 打印文件路径
        print(os.path.join(root, file))

In the code above, the os.walk() method recursively traverses all files and subfolders in the specified path and returns three values: the current folder path, a list of subfolders in the current folder, and a list of files in the current folder. These values can be used to access the paths of files and folders.

Please make sure to replace path_to_folder with the path of the folder you want to traverse.

bannerAds