Python Directory Traversal Guide
To recursively traverse folders, the walk() function of the os module can be used. This function returns a generator that recursively traverses all files and subfolders within a folder.
Here is an example code showing how to traverse folders using recursion.
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')
The function traverse_folder() in the above code takes a folder path as a parameter and uses the os.walk() function to iterate through the folder. The os.walk() function returns a generator that yields a tuple (root, dirs, files) for each iteration, where root is the current folder path being traversed, dirs is a list of subfolders in the current folder, and files is a list of files in the current folder.
In the loop, we can use os.path.join(root, file) to get the full path of each file and then perform the necessary operations, such as printing the file path.