代碼中包含注釋
文章目錄
- 一、我的需求
- 二、代碼
- 三、總結
一、我的需求
將 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 檔案了,
CSDN認證博客專家
神經網路
深度學習
Python
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/167236.html
標籤:其他
上一篇:2.2 Python編程規范
