用python编写代码达到列出某个文件夹及其子文件夹中包含搜索字符串的文件名字
时间: 2024-05-08 12:15:33 浏览: 9
以下是用Python编写的代码,可以列出某个文件夹及其子文件夹中包含搜索字符串的文件名字:
```python
import os
def search_files(folder_path, search_string):
for root, dirs, files in os.walk(folder_path):
for file in files:
if search_string in file:
file_path = os.path.join(root, file)
print(file_path)
# 用法示例:
search_files('/path/to/folder', 'search_string')
```
其中,`search_files` 函数接收两个参数:`folder_path` 表示要搜索的文件夹的路径,`search_string` 表示要搜索的字符串。该函数使用 `os.walk` 方法遍历指定文件夹及其子文件夹中的所有文件,如果文件名中包含搜索字符串,则输出该文件的路径。可以根据需要修改输出路径的方式,比如将路径存储到一个列表中返回。