我需要能够查找到子文件夹的下文件的代码
时间: 2024-03-07 13:48:44 浏览: 41
如果您需要遍历文件夹及其子文件夹下的所有文件,可以使用递归函数来实现。以下是 Python 查找文件夹及其子文件夹下所有文件的代码:
```python
import os
def find_files(folder_path):
# 遍历文件夹
for root, dirs, files in os.walk(folder_path):
# 遍历文件
for file in files:
# 打印文件路径
print(os.path.join(root, file))
# 遍历子文件夹
for dir in dirs:
# 递归查找子文件夹下的文件
find_files(os.path.join(root, dir))
# 文件夹路径
folder_path = 'path/to/folder'
# 查找文件
find_files(folder_path)
```
上述代码中,我们定义了一个名为 `find_files` 的递归函数,函数的参数是文件夹路径。在函数中,我们使用 `os.walk` 函数遍历文件夹及其子文件夹,然后遍历每个文件并打印文件路径。接着,我们遍历每个子文件夹,并递归调用 `find_files` 函数,以查找子文件夹下的文件。
最后,我们在主程序中调用 `find_files` 函数,并传入文件夹路径参数。这样,我们就可以查找文件夹及其子文件夹下的所有文件了。
阅读全文
相关推荐













