按属性匹配想要的数据
每个txt文件在Excel中为一行
# -*- coding: utf-8 -*-
import os
import openpyxl
from openpyxl import load_workbook
import xlrd
import xlwt
#相对路径
import frozen_dir
#时间后缀
import RandomName
SETUP_DIR = os.path.dirname(frozen_dir.app_path())
#from xlutils.copy import copy
"""txt数据写入excel,每个txt数据占一行"""
l = []
out_filename='宽带账号静态数据'+RandomName.RandomName()+'.xls'
file_path=SETUP_DIR+r'/xlsx/'+ out_filename#要写入的文件
'''xlwt'''
# 创建工作簿
f = xlwt.Workbook()
# 在工作簿中创建sheet
sheet = f.add_sheet('Sheet1')
'''xlrd'''
# 在已有excel中插入数据
#f = xlrd.open_workbook(file_path)
#wb = copy(f)
# 获取工作簿中的sheet
#sheet = f.get_sheet(0)
'''openpyxl'''
# 打开工作薄
#f = load_workbook(file_path)
#all_sheets = f.sheetnames
#print(all_sheets)
# 打开工作薄中具体的sheet
#work_sheet = all_sheets[i]
#sheet = work_book[work_sheet]
#sheet = f["Sheet1"]
#txt文件放置在文件夹中,用来获取文件夹内所有文件目录
pathDir = os.listdir(SETUP_DIR+r"\data")
#属性名
sheet.write(0, 0,'属性名1')
sheet.write(0, 1,'属性名2')
sheet.write(0, 2,'属性名3')
sheet.write(0, 3,'属性名4')
sheet.write(0, 4,'属性名5')
sheet.write(0, 5,'属性名6')
i = 1
for s in pathDir:
#把获取的文件路径整合,获取文件完整路径
newDir = os.path.join(r"D:\workspace\网络满意度\data", s)
print(newDir)
f1 = open(newDir, 'r', encoding='gbk')
lines = f1.readlines()
print(lines)
string = ""
for line in lines:
string += line
# 按行格式化输出
n = str(string).split(',')[0]
# 把每一行保存为一个数组
n2= str(n).split('\n')[0]
# 按分号划分,分别获取属性和值
n3= str(n2).split(':')[0]
n4= str(n2).split(':')[1]
print(n)
print(n2)
print(n3)
print(n4)
# str(str(n).split('\n')[0]).split(':')[0] #取属性
# str(str(n).split('\n')[0]).split(':')[1] #取数据
# 属性1
# sheet.write(0, 0, n3)
sheet.write(i, 0, n4)
# 属性2
# sheet.write(0, 1, str(str(n).split('\n')[0]).split(':')[0])
sheet.write(i, 1, str(str(n).split('\n')[31]).split(':')[1])
# 属性3
# sheet.write(0, 2, str(str(n).split('\n')[7]).split(':')[0])
sheet.write(i, 2, str(str(n).split('\n')[7]).split(':')[1])
# 属性4
# sheet.write(0, 3, str(str(n).split('\n')[8]).split(':')[0])
sheet.write(i, 3, str(str(n).split('\n')[8]).split(':')[1])
# 属性5
# sheet.write(0, 4, str(str(n).split('\n')[9]).split(':')[0])
sheet.write(i, 4, str(str(n).split('\n')[9]).split(':')[1])
# 属性6
# sheet.write(0, 4, str(str(n).split('\n')[9]).split(':')[0])
sheet.write(i, 5, str(str(n).split('\n')[1]).split(':')[1])
# 行数加一
i = i+1
print(i)
f.save(file_path)