import os
import xlwt
def txt_xls(filename, xlsname):
try:
f = open(filename)
xls = xlwt.Workbook() # 生成excel的方法,声明excel
sheet = xls.add_sheet('sheet', cell_overwrite_ok=True)
x = 0 # 在excel开始写的位置(y)
while True: # 循环读取文本里面的内容
line = f.readline() # 一行一行的读
if not line: # 如果没有内容,则退出循环
break
for i in range(len(line.split(' '))): # \t即tab健分,本处为空格分隔
item = line.split(' ')[i]
sheet.write(x, i, item) # x单元格经度,i单元格纬度
x += 1 # 另起一行
f.close()
xls.save(xlsname) # 保存为xls文件
except:
raise
if __name__ == '__main__':
xls_path = 'D:/pptest/data/px/IPX0002105001_mouse/data/'
txt_path = 'D:/pptest/data/px/IPX0002105001_mouse/data/'
files = os.listdir(txt_path)
print(files)
for file_name in files:
if '.txt' in file_name:
try:
txt_name = txt_path + file_name
xls_name = xls_path + file_name.split('.')[0] + '.xls'
print(txt_name)
print(xls_name)
txt_xls(txt_name, xls_name)
except:
pass ## 跳过一些系统隐藏文档
# ref
# https://blog.51cto.com/shijianfeng/3160791
py | 遍历目录里所有txt转xls
最新推荐文章于 2024-08-08 14:28:23 发布