一篇文章带你使用 Python 将 txt 文档内容存储到 excel 表中

代码中包含注释

一、我的需求

将 txt 文档中的数据,这样存储到 excel 表中:

在这里插入图片描述
存储的效果:

在这里插入图片描述

二、代码

import openpyxl

txtname = 'test_in.txt'
excelname = 'test_out.xlsx'

//读取 txt 文档:防止读取错误,读取时需要指定编码
fopen = open(txtname, 'r',encoding='utf-8')
lines = fopen.readlines()
//写入 excel表
file = openpyxl.Workbook()
sheet = file.active
# 新建一个sheet
sheet.title = "data"

i = 0
for line in lines:
    # strip 移出字符串头尾的换行
    line = line.strip('\n')
    # 用','替换掉'\t',很多行都有这个问题,导致不能正确把各个特征值分开
    line = line.replace("\t",",")
    line = line.split(',')
    # 一共7个字段
    for index in range(len(line)):
        sheet.cell(i+1, index+1, line[index])
    # 行数递增
    i = i + 1

file.save(excelname)

三、总结

这里的 openpyxl 库的版本是 3.0.4

本来是想着将 txt 文档的所有数据都存储到 excel 表中,代码没问题,最后发现 excel 表的最大行数是 1048576

导致没能全部读取。只好继续分析 txt 文档了。

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/108949626