python批量将端口描述文件转成excel

批量识别文件夹中的show int sw br文本文件,并将识别结果转换成excel文件,从而判断端口状态、端口描述等信息是否符合规定或者完整。

import re
import pandas as pd
import os
import openpyxl
from openpyxl import load_workbook
# 这篇代码用来识别端口状态
folder_path = 'E:/User/Desktop/新建文件夹/'
file_list = os.listdir(folder_path)


def modify_first_column(lst, new_value):
    # for row in lst循环遍历lst列表,在每一个循环中,new_value+每一行的第二个元素到尾,实现替换第一个元素的操作。
    return [[new_value] + row[1:] for row in lst]


hostname = ''
allDf = pd.DataFrame()
for file_name in file_list:
    file_path = os.path.join(folder_path, file_name)
    print(file_path)
    with open(file_path, 'r') as file:
        content = file.read()
        match = re.search(r'.*?(?=\#)', content)  # 在 content 中搜索主机名
        if match:
            hostname = match.group(0)
    # 识别首为“other”尾为“total”的一段文本,并且不包含首尾。
    start_keyword = "Other"
    end_keyword = "Total"
    # start_index:首字符索引。content.find():返回匹配发哦的关键词的第一个字符索引,len():关键词长度。所以start_index=首关键词后的第一个字符索引。
    start_index = content.find(start_keyword) + len(start_keyword)
    end_index = content.find(end_keyword)

    # 把需要的那段文本提取出来。
    text = content[start_index:end_index].strip()
    lines = text.strip().split('\n')  # 拆分为每行
    header = lines[0].split()  # 表头
    # 将lines数据用split分割为一个二元数组,从第二行开始lines[1:],1:表示的就是从第二行到结束所有的行。
    data = [line.split() for line in lines[1:]]  # 数据行
    print(hostname)
    new_data = modify_first_column(data, hostname)
    print(new_data)
    df = pd.DataFrame(new_data)
    allDf = allDf._append(df, ignore_index=True)
print(allDf)
allDf.to_excel('output.xlsx', index=False)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值