使用python,查询Windows电脑某个路径中匹配关键字内容的文档
时间: 2024-05-12 08:18:10 浏览: 76
可以使用Python内置的os和re模块来实现这个功能。具体代码如下:
```
import os
import re
def search_files(root_path, pattern):
result = []
pattern_re = re.compile(pattern)
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
file_content = f.read()
if pattern_re.search(file_content):
result.append(file_path)
return result
root_path = 'C:\\'
pattern = '关键字'
result = search_files(root_path, pattern)
print(result)
```
其中,`root_path`是需要搜索的根目录,`pattern`是匹配的关键字。这段代码将会搜索`root_path`及其子目录中所有包含`pattern`的文件,并返回文件路径的列表。
阅读全文