栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记录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, "转换完成!", "结果")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号