优化我的代码:import os import re import openpyxl path = r'C:\Users\WEI\Desktop\灌密钥工具\QFN76-刷脸整机-S1-WX-1-20220121\log\\' # 在这里输入路径 test ='I/工位-1: (.*?) 序列号\[T' test1 ='' def log1(path,test,test1): workbook = openpyxl.Workbook()# 创建一个工作簿 worksheet = workbook.active# 选定一个工作表 dirs = os.listdir(path) list =[] list1 =[] a = 1 for file in dirs: # print(file) # 输出所有文件和文件夹 file1 = open(rf'{path}{file}') info = file1.read() text1 = re.findall(test1, info) text = re.findall(test, info) # print(text) if None not in text: for i in range(len(text)): list1.append(text[i-1]) worksheet[f'A{a}'] = f'{text[i - 1]}' a = a + 1 if None not in text1: for i in range(len(text1)): list.append(text1[i-1]) worksheet[f'B{a}'] = f'{text1[i-1]}'# 在单元格A1中写入数据 workbook.save('example.xlsx')# 保存工作簿 log1(path,test,test1)
时间: 2024-03-03 19:47:20 浏览: 136
可以考虑以下几点进行优化:
1. 使用os.path.join()函数来拼接路径,避免在不同操作系统下出现路径分隔符不一致的问题。
2. 使用with语句来打开文件,避免手动关闭文件。
3. 将正则表达式的编译结果缓存起来,避免在每次循环中都重新编译,提高效率。
4. 可以使用pandas库来更方便地处理Excel文件,避免手动编写写入Excel文件的代码。
优化后的代码如下:
```
import os
import re
import openpyxl
import pandas as pd
path = r'C:\Users\WEI\Desktop\灌密钥工具\QFN76-刷脸整机-S1-WX-1-20220121\log\\'
test = r'I/工位-1: (.*?) 序列号\[T'
test1 = r''
workbook = openpyxl.Workbook()
worksheet = workbook.active
list = []
list1 = []
a = 1
pattern = re.compile(test)
pattern1 = re.compile(test1)
for file in os.listdir(path):
file_path = os.path.join(path, file)
with open(file_path, 'r') as f:
info = f.read()
text = pattern.findall(info)
text1 = pattern1.findall(info)
if text:
list1.extend(text)
for i in range(len(text)):
worksheet[f'A{a}'] = text[i]
a += 1
if text1:
list.extend(text1)
for i in range(len(text1)):
worksheet[f'B{a}'] = text1[i]
a += 1
workbook.save('example.xlsx')
# 使用pandas库更方便地写入Excel文件
df = pd.DataFrame({'序列号': list1, '其他信息': list})
df.to_excel('example.xlsx', index=False)
```
这样优化后的代码可以更高效地读取日志文件,并将结果写入Excel文件。使用pandas库还可以更方便地处理Excel文件,提高代码的可读性。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![PcbLib](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![PcbLib](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pcblib](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)