Python實現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法示例
本文實例講述了Python實現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法。分享給大家供大家參考,具體如下:
這里的txt文件內(nèi)容格式為:
892天平天國定都在?A開封B南京C北京(B)
Python代碼如下:
# coding=utf-8
'''''
main function:主要實現(xiàn)把txt中的每行數(shù)據(jù)寫入到excel中
'''
#################
#第一次執(zhí)行的代碼
import xlwt #寫入文件
import xlrd #打開excel文件
import os
txtFileName = 'questions.txt'
excelFileName = 'questions.xls'
if os.path.exists(excelFileName):
os.remove(excelFileName)
fopen = open(txtFileName, 'r')
lines = fopen.readlines()
#新建一個excel文件
file = xlwt.Workbook(encoding='utf-8',style_compression=0)
#新建一個sheet
sheet = file.add_sheet('data')
############################
#寫入寫入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)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作Excel表格技巧總結(jié)》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python 將日期戳(五位數(shù)時間)轉(zhuǎn)換為標(biāo)準(zhǔn)時間
這篇文章主要介紹了python 將日期戳(五位數(shù)時間)轉(zhuǎn)換為標(biāo)準(zhǔn)時間的實現(xiàn)方法,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07
python自動化測試selenium操作checkbox和radiobox技術(shù)
這篇文章主要為大家介紹了python自動化測試selenium核心技術(shù)操作checkbox和radiobox的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
windows系統(tǒng)IIS部署Django項目的實踐
采用IIS服務(wù)器部署相比django提供的開發(fā)者服務(wù)器具有更好的并發(fā)訪問能力,性能更加穩(wěn)定,本文主要介紹了windows系統(tǒng)IIS部署Django項目的實踐,具有一定的參考價值,感興趣的可以了解一下2022-03-03
Python利用psutil獲取CPU與內(nèi)存等硬件信息
psutil是Python的一個第三方庫,提供了各種強大的硬件信息查閱功能,這篇文章主要為大家介紹了如何利用psutil獲取CPU與內(nèi)存等硬件信息,需要的可以參考一下2023-07-07
Python加載數(shù)據(jù)的5種不同方式(收藏)
這篇文章主要介紹了Python加載數(shù)據(jù)的5種不同方式(收藏),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

