Python实现读取txt文件并转换为excel的方法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现读取txt文件并转换为excel的方法。分享给大家供大家参考,具体如下:

这里的txt文件内容格式为:

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

Python代码如下:

# coding=utf-8
'''''
main function:主要实现把txt中的每行数据写入到excel中
'''
#################
#第一次执行的代码
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)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作Excel表格技巧总结》、《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

基于数据归一化以及Python实现方式

数据归一化: 数据的标准化是将数据按比例缩放,使之落入一个小的特定区间,去除数据的单位限制,将其转化为无量纲的纯数值,便于不同单位或量级的指标能够进行比较和加权。 为什么要做归一化: 1...

python3使用flask编写注册post接口的方法

使用python3的Flask库写了一个接口,封装了很多东西,仅供参考即可! 代码如下: #!/usr/bin/python3 # -*- coding: utf-8 -*- im...

Python设计模式编程中解释器模式的简单程序示例分享

Python设计模式编程中解释器模式的简单程序示例分享

模式特点:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。 我们来看一下下面这样的程序结构: class Context: de...

Python读取csv文件分隔符设置方法

Windows下的分隔符默认的是逗号,而MAC的分隔符是分号。拿到一份用分号分割的CSV文件,在Win下是无法正确读取的,因为CSV模块默认调用的是Excel的规则。 所以我们在读取文件...

为Python的web框架编写MVC配置来使其运行的教程

为Python的web框架编写MVC配置来使其运行的教程

现在,ORM框架、Web框架和配置都已就绪,我们可以开始编写一个最简单的MVC,把它们全部启动起来。 通过Web框架的@decorator和ORM框架的Model支持,可以很容易地编写一...