本文實(shí)例講述了Python實(shí)現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法。分享給大家供大家參考,具體如下:
這里的txt文件內(nèi)容格式為:
892天平天國(guó)定都在?A開(kāi)封B南京C北京(B)
Python代碼如下:
# coding=utf-8 ''''' main function:主要實(shí)現(xiàn)把txt中的每行數(shù)據(jù)寫(xiě)入到excel中 ''' ################# #第一次執(zhí)行的代碼 import xlwt #寫(xiě)入文件 import xlrd #打開(kāi)excel文件 import os txtFileName = 'questions.txt' excelFileName = 'questions.xls' if os.path.exists(excelFileName): os.remove(excelFileName) fopen = open(txtFileName, 'r') lines = fopen.readlines() #新建一個(gè)excel文件 file = xlwt.Workbook(encoding='utf-8',style_compression=0) #新建一個(gè)sheet sheet = file.add_sheet('data') ############################ #寫(xiě)入寫(xiě)入a.txt,a.txt文件有20000行文件 i=0 j=0 for line in lines: indexA = line.find('A') questionStr = line[0:indexA] questionStr.lstrip() indexB = line.find('B') answerA = line[indexA:indexB] indexC = line.find('C') indexE = line.find('(') answerB = '' if indexC>0: answerB = line[indexB:indexC] else: answerB = line[indexB:indexE] indexD = line.find('D') answerC = '' answerD = '' if indexD>0: answerC = line[indexC:indexD] answerD = line[indexD:indexE] else: answerC = line[indexC:indexE] answer = line[line.find('('):line.find(')')] cindex = 0 questionStrCopy = '' for c in questionStr: if cindex<3: if c>='0' and c<='9': questionStrCopy = questionStr[cindex+1:] cindex = cindex + 1 answerA = answerA[1:] answerB = answerB[1:] answerC = answerC[1:] answerD = answerD[1:] answer = answer.strip('(') print answer print questionStrCopy, answerA, answerB, answerC, answerD, answer questionStrCopy = questionStrCopy.lstrip() if questionStrCopy=='' or answerA=='' or answer=='': continue sheet.write(i, 0 , questionStrCopy) sheet.write(i, 1 , answerA) sheet.write(i, 2 , answerB) sheet.write(i, 3 , answerC) sheet.write(i, 4 , answerD) sheet.write(i, 5 , answer) i = i + 1 file.save(excelFileName)
文章題目:Python實(shí)現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法示例-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)源:http://www.chinadenli.net/article16/coepdg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、全網(wǎng)營(yíng)銷(xiāo)推廣、定制開(kāi)發(fā)、標(biāo)簽優(yōu)化、電子商務(wù)、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容