查找指定目录下所有子目录文件中是否存在关键字
2024-04-23 19:25 Tanwheey 阅读(24) 评论(0) 编辑 收藏 举报## Python2.7
# -*- coding: gb18030 -*-
import os
import io
import sys
reload(sys)
sys.setdefaultencoding('gb18030')
path = r'D:\k1_total_quantity_scripts\Suites\Onetrack\Design Vaildation TEST\Feature TEST\FE TEST\NVME'
for root, _, files in os.walk(path):
if len(files) > 0:
for f in files:
position = root + '\\' + f
with io.open(position, encoding='gb18030', errors='ignore') as ff:
content = ff.read()
lines = content.splitlines()
for line in lines:
if '0xc5' in line.strip(): # 查找含有关键字的行
with open('log.txt', 'a') as fff:
fff.write(f + ' , '+line.strip() + '\n') # 保存含有关键字的文件
## Python 3 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') #改变标准输出的默认编码 path = r'D:\NewProgram\Unionmem_SSD\TestCases\03_产品集成测试\201_ESSD特性测试\303_FE_TEST\NVME' for root, _, files in os.walk(path): if len(files) > 0: for f in files: position = root + '\\' + f with io.open(position, encoding='utf-8', errors='ignore') as ff: content = ff.read() lines = content.splitlines() for line in lines: if '0xc5' in line.strip(): # 查找含有关键字的行 with open('log.txt', 'a') as fff: fff.write(f + ' , '+line.strip() + '\n') # 保存含有关键字的文件
Python3环境下,生成TXT文件后,在文件中选择“以GBK重新加载”显示文件。且文件设置中的文件编码中的全局编码、项目编码、属性文件默认编码都设置成utf-8
编码名称 | 用途 |
utf8 | 所有语言 |
gbk | 简体中文 |
gb2312 | 简体中文 |
gb18030 | 简体中文 |
big5 | 繁体中文 |
big5hkscs | 繁体中文 |