python把字典数据写入excel(python读取txt文本信息写入excel)
每天巡检脚本生成的巡检报告
文本信息如下:
python代码
#!/usr/bin/env python
# -*-coding:utf8 -*-
# @Time : 2020/11/17 16:31
# @Author : riches
# @Site :
# @File : tiqu1.py
# @Software: PyCharm
import os
import re
import xlrd, xlwt
def cpu(data):
return data.split()[5]
def mem(data):
return data.split()[3]
def disk(data):
return data.split()[4]
def disk1(data):
return data.split()[4]
def disk2(data):
return data.split()[4]
def find_files(s_path):
res = {}
file_list = os.listdir(s_path)
for filename in file_list:
abs_filename = os.path.join(s_path, filename)
if os.path.isfile(abs_filename):
# 打开文件
with open(abs_filename, "r", encoding="utf8") as f:
for line in f:
if re.search('mem.*cpu',line) is not None:
#import pdb;pdb.set_trace()
m2 = mem(line)
m1 = cpu(line)
if re.search('/dev/sda3.*/',line) is not None:
d1 = disk(line)
if re.search('/dev/sdb1.*/home',line) is not None:
d2 = disk1(line)
if re.search('/dev/sdc1.*/home', line) is not None:
d3 = disk2(line)
break
res[abs_filename] = (m1,m2,d1,d2,d3)
elif os.path.isdir(abs_filename):
find_files(abs_filename)
else:
print("不是文件夹,也不是文件")
return res
#创建excel 文件
def write_excel(data):
writebook = xlwt.Workbook() # 打开一个excel
sheet = writebook.add_sheet('data') # 在打开的excel中添加一个sheet
# 添加表头
sheet.write(0, 0, '文件名')
#sheet.write(0, 1, '内存占比')
#sheet.write(0, 2, 'CPU占比')
sheet.write(0, 1, 'CPU占比')
sheet.write(0, 2, '内存占比')
sheet.write(0, 3, '硬盘根占比')
sheet.write(0, 4, 'home占比')
sheet.write(0, 5, 'data占比')
# sheet.write(0, 5, '18:00.1流量')
# sheet.write(0, 6, '86:00.1流量')
# 65535 最大行,可以自行拆分
for index, item in enumerate(data):
sheet.write(index 1, 0, item) # 文件名
sheet.write(index 1, 1, data[item][0])
sheet.write(index 1, 2, data[item][1])
sheet.write(index 1, 3, data[item][2])
sheet.write(index 1, 4, data[item][3])
sheet.write(index 1, 5, data[item][3])
writebook.save("D:\\tongji\\192.168.1.1.xls")
if __name__ == "__main__":
s = r"D:\tqtest\" # 更换自己的路径
res = find_files(s)
write_excel(res)
运行效果如下:
,
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com