怎么用python读取txt文件里指定行的内容,并导入excel

如题所述

def eachlineof(filename):
''' 逐行读取给定的文本文件,返回行号、剔除末尾空字符的行内容 '''
with open(filename) as handle:
for lno, line in enumerate(handle):
yield lno+1, line.strip()

另外: 读写excel需要第三方类库,可以考虑下载安装xlrd, xlwt

写excel表
写excel表要用到xlwt模块,官网下载(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:
1、导入模块

复制代码代码如下:
import xlwt

2、创建workbook(其实就是excel,后来保存一下就行)

复制代码代码如下:
workbook = xlwt.Workbook(encoding = 'ascii')

3、创建表

复制代码代码如下:
worksheet = workbook.add_sheet('My Worksheet')

4、往单元格内写入内容

复制代码代码如下:
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')

5、保存

复制代码代码如下:
workbook.save('Excel_Workbook.xls')

由于我的需求比较简单,所以这上面没遇到什么问题,唯一的就是建议还是用ascii编码,不然可能会有一些诡异的现象。

当然xlwt功能远远不止这些,他甚至可以设置各种样式之类的。附上一点例子

复制代码代码如下:

Examples Generating Excel Documents Using Python's xlwt

Here are some simple examples using Python's xlwt library to dynamically generate Excel documents.
Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffi
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-01-26

解答如下:

    首先打开txt文件,使用open(txtName),进行一行一行的读;

    如果需要的话,对每行的数据进行解析;

    导入xlrd,xlwt进行excel读写:

    workbook = xlwt.Workbook(encoding = 'ascii')
    worksheet = workbook.add_sheet('sheet1')
    worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
    workbook.save('Excel_Workbook.xls')

    大致的流程如上面所示。

相似回答