python3 一些基础操作笔记
读取文件模板
1 # -*- coding: utf-8 -*- 2 import glob 3 filepath = glob.glob('**/kernel_log*', recursive=True) 4 print(filepath) 5 6 for path in filepath: 7 with open(path, mode='r', encoding='utf-8') as f: 8 print("filepath is " + path) 9 line_num = 1 10 for line in f.read().splitlines(): 11 if cam_err in line: 12 print(str(line_num)+":"+line) 13 line_num += 1 14 print("-"*10 + "end" + "-"*10)
一个示例
# -*- coding: utf-8 -*- import glob import os filepath = glob.glob('**/kernel_log*', recursive=True) current_path = os.path.dirname(os.path.abspath(__file__)) result_path = current_path + "/result.txt" if os.path.exists(result_path): os.remove(result_path) # print(result_path) # print(filepath) cam_err = "cam_err" cam_err_detail = {"overflow": "overflow问题,请排查", "probe fail": "probe失败,排查上电或sensor_id", "CCI time wait": "请检查上电时序和i2c", "process died": "检查上层crash"} def get_err_detail(error_line, line_number, fd): for err_key in cam_err_detail: if err_key in error_line: error_line_new = "error line: " + str(line_number) + ':' + error_line + '\n' error_line_tips = cam_err_detail.get(err_key) + '\n' print(error_line_new, end=" ") print(error_line_tips, end=" ") writelines = [error_line_new, error_line_tips] fd.writelines(writelines) for path in filepath: with open(path, mode='r', encoding='utf-8') as f, open(result_path, mode='a+', encoding='utf-8') as f2: filename = "filepath: " + path + '\n' print(filename, end=" ") f2.write(filename) line_num = 1 for line in f.read().splitlines(): if cam_err in line: get_err_detail(line, line_num, f2) line_num += 1 print("-"*10 + "end" + "-"*10) f2.write('\n')