Recursively Traverse Folders in Python
In Python, you can use the os module to traverse folders. Below is an example of traversing folders using recursion.
import os
def traverse_folder(folder_path):
# 获取文件夹下的所有文件和文件夹
files = os.listdir(folder_path)
for file in files:
# 拼接文件路径
file_path = os.path.join(folder_path, file)
if os.path.isdir(file_path):
# 如果是文件夹,则递归遍历
traverse_folder(file_path)
else:
# 如果是文件,则打印文件路径
print(file_path)
# 调用函数遍历文件夹
traverse_folder('your_folder_path')
The traverse_folder function in the code above is used to recursively navigate through folders, with the folder_path parameter representing the path to the folder to be traversed. Initially, all files and folders within the folder are retrieved. It then determines whether each path is a folder or a file. If it is a folder, the traverse_folder function is called recursively. If it is a file, the file path is printed.
It is important to note that when calling the traverse_folder function, you need to pass in the folder path to be traversed.