python提取多个文件夹下面多个.log文件里面指定内容并收集结果到TXT上面
时间: 2023-06-16 09:08:21 浏览: 179
可以使用Python内置的os和re模块来实现。具体步骤如下:
1. 遍历多个文件夹,找到所有的.log文件;
2. 逐个打开.log文件,使用正则表达式匹配指定内容,并将结果保存到列表中;
3. 将列表中的所有结果写入到一个TXT文件中。
下面是一个示例代码,仅供参考:
```python
import os
import re
# 指定需要匹配的内容
pattern = re.compile(r'Test: (\d+)')
# 遍历多个文件夹,找到所有的.log文件
folders = ['folder1', 'folder2']
log_files = []
for folder in folders:
for file in os.listdir(folder):
if file.endswith('.log'):
log_files.append(os.path.join(folder, file))
# 逐个打开.log文件,匹配指定内容,并将结果保存到列表中
results = []
for file in log_files:
with open(file, 'r') as f:
for line in f:
match = pattern.search(line)
if match:
results.append(match.group(1))
# 将列表中的所有结果写入到一个TXT文件中
with open('results.txt', 'w') as f:
f.write('\n'.join(results))
```
其中,`folders`为需要遍历的文件夹列表,`pattern`为需要匹配的内容,本示例中为匹配形如`Test: 123`的内容。最终结果将保存在`results.txt`文件中。
阅读全文
相关推荐
















