用re查询在指定文件夹中包含关键词的所有文件
时间: 2024-04-13 10:29:56 浏览: 20
您可以使用Python的re模块来实现这个功能。下面是一个示例代码,它使用re模块来查询指定文件夹中包含关键词的所有文件:
```python
import os
import re
def search_files(folder_path, keyword):
files = []
pattern = re.compile(keyword)
for root, dirs, filenames in os.walk(folder_path):
for filename in filenames:
file_path = os.path.join(root, filename)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
if re.search(pattern, content):
files.append(file_path)
return files
# 指定文件夹路径和关键词
folder_path = 'your_folder_path'
keyword = 'your_keyword'
# 执行搜索并打印结果
result = search_files(folder_path, keyword)
for file in result:
print(file)
```
请将`your_folder_path`替换为您要搜索的文件夹路径,将`your_keyword`替换为您要查询的关键词。该代码将递归地搜索指定文件夹中的所有文件,并返回包含关键词的文件路径列表。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![sh](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)