|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #!/bin/python
- # -*- encoding=utf-8 -*-
- import openpyxl
- from textfsm import TextFSM
- from io import BytesIO
- # 打开txt文件
- with open('var_data.txt', 'r') as f:
- data = f.read()
-
- # 打开Excel文件并创建工作表
- wb = openpyxl.Workbook()
- ws = wb.active
- # 设置表头
- header = ['信息', '值']
- ws.append(header)
- # 解析txt文件内容
- template = '''Value Name=(.*?)\S+Value=(.*?)\n'''
- print(template)
- re_table = TextFSM(BytesIO(template.encode('utf-8')))
- data = data.strip()
- # Debug模式
- debug = True
- if debug:
- re_table.debug = True
- for line in data.split('\n'):
- re_table._Debug(line)
- fsm_results = re_table.ParseText(data)
- # 将结果写入Excel工作表
- for result in fsm_results:
- ws.append(result)
- # 保存Excel文件
- wb.save('result.xlsx')
复制代码
var_data.txt文本数据如下,要求=前面的写如excel第一列,后面的写入excel第二列,
aa=bb
cc==dd
ee=ff
以上脚本报如下错误,提示18行template格式有问题
- File "write_in.py", line 19, in <module>
- re_table = TextFSM(BytesIO(template.encode('utf-8')))
- File "/usr/local/lib/python3.4/dist-packages/textfsm/parser.py", line 584, in __init__
- self._Parse(template)
- File "/usr/local/lib/python3.4/dist-packages/textfsm/parser.py", line 682, in _Parse
- self._ParseFSMVariables(template)
- File "/usr/local/lib/python3.4/dist-packages/textfsm/parser.py", line 742, in _ParseFSMVariables
- raise TextFSMTemplateError('No Value definitions found.')
- textfsm.parser.TextFSMTemplateError: No Value definitions found.
复制代码
#!/bin/python
# -*- encoding=utf-8 -*-
import openpyxl
from textfsm import TextFSM
from io import BytesIO
# 打开txt文件
with open('var_data.txt', 'r') as f:
data = f.read()
# 打开Excel文件并创建工作表
wb = openpyxl.Workbook()
ws = wb.active
# 设置表头
header = ['信息', '值']
ws.append(header)
# 解析txt文件内容
# 模板应该这样写
template = '''Value Name (.+)
Value Value (.+)
Start
^${Name}=${Value} -> Record
'''
print(template)
re_table = TextFSM(BytesIO(template.encode('utf-8')))
print(dir(re_table))
print(re_table)
data = data.strip()
# 这几行代码是想做什么,TextFSM 对象没有 _Debug 方法
'''
# Debug模式
debug = True
if debug:
re_table.debug = True
for line in data.split('\n'):
re_table._Debug(line)
'''
fsm_results = re_table.ParseText(data)
# 将结果写入Excel工作表
for result in fsm_results:
ws.append(result)
# 保存Excel文件
wb.save('result.xlsx')
|
|