jackyshan

导航

 
#!/bin/env python
# -*- encoding: utf-8 -*-
import datetime
import time
import os
import sys
import xlwt #需要的模块
import re
from xlutils.copy import copy
import xlrd

def txt2xls(filename,xlsname):  #文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名
    print 'converting xls ... '
    #m = re.split('\.', filename)

    f = open(filename)   #打开txt文本进行读取
    ip = filename
    m = re.match(r'(.*)\..{3}', ip)
    ip = m.group(1)
    #xls = xlrd.open_workbook(gConst['xls']['xlsname'])
    xls = xlrd.open_workbook(xlsname)
    newxls = copy(xls)
    newx = newxls.get_sheet(0)
    y = 0
    newx.write(x,y,ip)
    y = 1
    print x,y,filename
    while True:  #循环,读取文本里面的所有内容
        line = f.readline() #一行一行读取
        if not line:  #如果没有内容,则退出循环
            break
        for i in line.split('\t'):#读取出相应的内容写到x
            if i == '\n':break
            if i == '':continue
            try:
                item=i.strip().decode('utf8')
            except:
                item=i.strip().decode('GBK')
            if item == (u'操作系统'):break
            if item == (u'CPU'):break
            if item == (u'RAM'):break
            if item == (u'主板'):break
            if item == (u'图像'):break
            if item == (u'硬盘'):break
            if item == (u'光盘驱动器'):break
            if item == (u'音频'):break
            newx.write(x,y,item)
            y += 1 #另起一列
            #x += 1 #另起一行
            #y = 0  #初始成第一列
    f.close()
    newxls.save(xlsname)
    #exit(0)
    #xls.save(xlsname+'.xls') #保存

if __name__ == "__main__":
    x = 1                #在excel开始写的位置(y)
    y = 0                #在excel开始写的位置(x)
    for i in range(101,151):
        filename = repr(i) + '.txt'
        xlsname = 'ip1.xls'
        try:
            txt2xls(filename,xlsname)
            x += 1
        except IOError, e:
            print e
            pass
        

 

posted on 2013-11-20 11:26  jackyshan  阅读(1494)  评论(0编辑  收藏  举报