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

首頁 > 編程 > Python > 正文

Python實現(xiàn)讀取txt文件并轉換為excel的方法示例

2020-01-04 15:04:00
字體:
來源:轉載
供稿:網友

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

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

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

Python代碼如下:

# coding=utf-8'''''main function:主要實現(xiàn)把txt中的每行數(shù)據(jù)寫入到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教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 亚东县| 静宁县| 长宁县| 香河县| 饶阳县| 大方县| 扶绥县| 翼城县| 芦山县| 巴马| 吐鲁番市| 望奎县| 蒙阴县| 政和县| 肥东县| 嵊泗县| 南城县| 松桃| 綦江县| 黄冈市| 鄂托克旗| 西盟| SHOW| 沙雅县| 青田县| 芜湖县| 湖南省| 延津县| 格尔木市| 龙井市| 武陟县| 广德县| 南康市| 清徐县| 张家港市| 平乡县| 伽师县| 道真| 桃园县| 镇康县| 岢岚县|