记录python 写工具的第一次 ,将txt文件转换到excel,使用openpyxl,win32,os,sys,datatime

# from datetime import time
# import re
# import xlwt
# import xlrd
# from ast import If
# from filecmp import cmp
import os
from dateutil.parser import parse
# import xlsxwriter
import win32api
import sys
import datetime
import openpyxl


filenames = []  #文件列表
txt_filenames = []  #电池数据列表

column_time = 1
column_index = 2
column_glu_adc = 3
column_ntc_adc = 4
column_bat_adc = 5
column_bat_vol = 6

#读取本地时间
time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# time_str = str(time.year) + '_' + str(time.month) + '_' + str(time.day) + '_' + str(time.hour ) +  '_' + str(time.minute) + '_' + str(time.second)
time_str = str(time)
print(time_str)


#识别文件路径
path = []
path = sys.argv
print("path:" + path[-1])
#读取文件路径
file_path = path[-1]
file_path_turple = os.path.split(path[-1])
#分割文件夹路径和文件名
directory_path = file_path_turple[0]
file_name = file_path_turple[1]

if directory_path +"\\"+ file_name != file_path:
    print(directory_path +"\\"+ file_name)
    print(file_path)
    win32api.MessageBox(0,"文件路径有转义符")

#读取路径中的文件
filenames = os.listdir(directory_path)
if str(os.path.splitext(file_name)[1]).lower() == '.txt':
    if file_name in filenames:
            txt_filenames.append(file_name)
    else:
        win32api.MessageBox(0,"文件未找到或者文件路径有转义符")
else:
    for filename in filenames:
        if str(os.path.splitext(filename)[1]).lower() == '.txt':
            txt_filenames.append(filename)
print(txt_filenames)

#读取txt文件
for txt_filename in txt_filenames:
    file_name = str(os.path.splitext(txt_filename)[0])
    out_excelFileName = file_name + '_'+ time_str + ".xlsx"
    
    #判断输出文件存在
    if os.path.exists(out_excelFileName):
        os.remove(out_excelFileName)

    #新建excel
    out_excel = openpyxl.Workbook()
    row = 1#行
    out_file_sheet = out_excel.active
    out_file_sheet.cell(row, column_time, "时间")
    out_file_sheet.cell(row, column_index, "序号",)
    out_file_sheet.cell(row, column_glu_adc, "血糖ADC")
    out_file_sheet.cell(row, column_ntc_adc, "NTC ADC")
    out_file_sheet.cell(row, column_bat_adc, "电池ADC")
    out_file_sheet.cell(row, column_bat_vol, "电池电压值")
    out_file_sheet.column_dimensions['A'].width=23
    out_file_sheet.column_dimensions['B'].width=10
    out_file_sheet.column_dimensions['C'].width=10
    out_file_sheet.column_dimensions['D'].width=10
    out_file_sheet.column_dimensions['E'].width=10
    out_file_sheet.column_dimensions['F'].width=18
    #添加数据
    row = row + 1
    try:
        fopen = open(str(directory_path +"\\"+ txt_filename), 'r' , encoding='gbk')
    except Exception as err_code:
         print(err_code)        
        #  os.system("pause")
    else:
        print(path)
        line = 'a'
        while line:
            try:
                line = fopen.readline()
            except Exception as err_code:
                print(err_code)
                continue
            else:
                index_index = line.find("index")
                index_glu = line.find("glu")
                index_ntc = line.find("ntc")
                index_bat = line.find("bat")
                if(index_index != -1 & (index_glu != -1 | index_ntc != -1 | index_bat != -1)):
                    if(index_index != -1):
                        # 时间
                        time = line[0:index_index].strip().strip(',').strip('[').strip(']')
                        time ="".join(filter(lambda glu:glu in'0123456789.', time))
                        out_file_sheet.cell(row, column_time, parse(time)).number_format = 'YYYY/MM/DD hh:mm:ss'
                        print(parse(time),end = " ")
                    if(index_glu != -1):
                        #序号
                        index = line[index_index + 6:index_glu].strip().strip(',').strip('[').strip(']')
                        index ="".join(filter(lambda index:index in'0123456789.', index))
                        if int(index) == 65535:
                            index = -1
                        out_file_sheet.cell(row, column_index, int(index))
                        print("index:"+str(index),end = ' ')
                        glu = line[index_glu:index_glu + 8].strip().strip(',').strip('[').strip(']')
                        #血糖
                        glu ="".join(filter(lambda glu:glu in'0123456789.', glu))
                        out_file_sheet.cell(row, column_glu_adc, int(glu))
                        print("glu:"+glu,end = " ")
                    if(index_ntc != -1):
                        #ntc
                        ntc = line[index_ntc:index_ntc + 8].strip().strip(',').strip('[').strip(']')
                        ntc ="".join(filter(lambda ntc:ntc in'0123456789.', ntc))
                        out_file_sheet.cell(row, column_ntc_adc, int(ntc))
                        print("ntc:"+ntc,end = " ")
                    if(index_bat != -1):
                        #bat_adc
                        bat_adc = line[index_bat:index_bat + 8].strip().strip(',').strip('[').strip(']')
                        bat_adc ="".join(filter(lambda bat_adc:bat_adc in'0123456789.', bat_adc))
                        out_file_sheet.cell(row, column_bat_adc, int(bat_adc))
                        print("bat_adc:"+bat_adc)
                        #bat_vol
                        equation = int(bat_adc)*3600/4096
                        out_file_sheet.cell(row, column_bat_vol, equation)
                if index_glu == -1 & index_ntc == -1 & index_bat == -1:
                    row = row 
                else:
                    row = row + 1
    out_excel.save(directory_path + "\\" + out_excelFileName)
win32api.MessageBox(0, "转换完成!", "结果")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值