代码中包含注释
文章目录
一、我的需求二、代码三、总结
一、我的需求
将 txt 文档中的数据,这样存储到 excel 表中:
存储的效果:
二、代码
import openpyxl
txtname
= 'test_in.txt'
excelname
= 'test_out.xlsx'
fopen
= open(txtname
, 'r',encoding
='utf-8')
lines
= fopen
.readlines()
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 文档了。
南淮北安
认证博客专家
深度学习
Java
Python
牛年大吉,牛气冲天!!!