-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathtxttoxls.py
39 lines (37 loc) · 1.47 KB
/
txttoxls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by xiaoqin00 on 2017/7/10
import datetime
import time
import os
import sys
import xlwt #需要的模块
from optparse import OptionParser
def txt2xls(filename,xlsname): #文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名
print 'converting xls ... '
f = open(filename) #打开txt文本进行读取
x = 0 #在excel开始写的位置(y)
y = 0 #在excel开始写的位置(x)
xls=xlwt.Workbook()
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().decode('utf8')
sheet.write(x,y,item)
y += 1 #另起一列
x += 1 #另起一行
y = 0 #初始成第一列
f.close()
# xls.save(xlsname+'.xls') #保存
xls.save(xlsname)
if __name__ == "__main__":
parser=OptionParser(usage='%prog [options]')
parser.add_option('-i','--in',dest='input',help='input file')
parser.add_option('-o','--out',dest='output',help='output file')
(options,args)=parser.parse_args()
filename = options.input
xlsname = options.output
txt2xls(filename,xlsname)