原创地址:https://blog.csdn.net/levy_cui/article/details/82252183
# !/usr/bin/python
# -*- coding: utf-8 -*-
# 创建时间 : 2020/1/3 14:33
# -------------------------------------------------------------------------------
# Purpose: txt转换成Excel
# use: python txt2excel.py out.txt ABC
# -------------------------------------------------------------------------------
import datetime
import time
import os
import sys
import xlwt # 需要的模块
def txt2xls(filename, xlsname): # 文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名
print('converting xls ... ')
f = open(filename,"r",encoding="utf8") # 打开txt文本进行读取
x = 0 # 在excel开始写的位置(y)
y = 0 # 在excel开始写的位置(x)
xls = xlwt.Workbook(encoding = 'utf8')
sheet = xls.add_sheet('sheet1', cell_overwrite_ok=True) # 生成excel的方法,声明excel
while True: # 循环,读取文本里面的所有内容
line = f.readline() # 一行一行读取
if not line: # 如果没有内容,则退出循环
break
for i in line.split('\t'): # 读取出相应的内容写到x
item = i.strip()
sheet.write(x, y, item)
y += 1 # 另起一列
x += 1 # 另起一行
y = 0 # 初始成第一列
f.close()
xls.save(xlsname) # 保存
if __name__ == "__main__":
filename = r"F:\2019-12-17-表演购物类poi筛选\result\all_res_new.txt"
xlsname = r"F:\2019-12-17-表演购物类poi筛选\result\all_res_new.xls"
txt2xls(filename, xlsname)