国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現讀取txt文件并轉換為excel的方法示例

2020-02-23 00:08:31
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現讀取txt文件并轉換為excel的方法。分享給大家供大家參考,具體如下:

這里的txt文件內容格式為:

892天平天國定都在?A開封B南京C北京(B)

Python代碼如下:

# coding=utf-8'''''main function:主要實現把txt中的每行數據寫入到excel中'''##################第一次執(zhí)行的代碼import xlwt #寫入文件import xlrd #打開excel文件import ostxtFileName = '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)#新建一個sheetsheet = file.add_sheet('data')#############################寫入寫入a.txt,a.txt文件有20000行文件i=0j=0for 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 + 1file.save(excelFileName)

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python操作Excel表格技巧總結》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 淳安县| 沂水县| 会东县| 定安县| 商丘市| 德州市| 钟山县| 濉溪县| 靖安县| 通许县| 承德市| 七台河市| 慈溪市| 通化县| 铁岭县| 山阴县| 宽甸| 永仁县| 上杭县| 定州市| 南雄市| 高邑县| 高密市| 得荣县| 辽阳市| 锡林浩特市| 南平市| 临桂县| 龙陵县| 六枝特区| 武乡县| 大埔区| 裕民县| 台东市| 和林格尔县| 铜山县| 旬邑县| 浑源县| 时尚| 安溪县| 县级市|