基于python将txt文件数据导出至excel中

本文是基于python处理包含大量数据的TXT文件前传,还有下篇哦。

用到的库有xlwt,只需要这个写入excel的库就行了,直接上代码:

import xlwt
def txt2xls(filename,xlsname): 
    f = open(filename)   #打开txt文本进行读取
    x = 0                #在excel开始写的位置(y)
    y = 0                #在excel开始写的位置(x)
    xls=xlwt.Workbook()
    sheet = xls.add_sheet('sheet1',cell_overwrite_ok=True)
    while True:  #循环,读取文本里面的所有内容
        line = f.readline() #一行一行读取
        if not line:  #如果没有内容,则退出循环
            break
        for i in line.split('\t'):#读取出相应的内容写到x
#            item=i.strip().decode('utf8')
            item=i.strip()
            sheet.write(x,y,item)
            y += 1 #另起一列
        x += 1 #另起一行
        y = 0  #初始成第一列
    f.close()
    xls.save(xlsname+'.xls') #保存

filename='E:\\pycharmcommunity\project\\txt_to_excel\\fi-120-050.txt'
xlsname='fi-120-050'
txt2xls(filename,xlsname)

以函数的形式写方便更好的调用,每行含义都做了注释,方便你们看也方便我以后复习。

执行结果:

基于python将txt文件数据导出至excel中_第1张图片

基于python将txt文件数据导出至excel中_第2张图片 

 对比一致,结束。

你可能感兴趣的:(python学习笔记,python,开发语言,excel)