[英]Python - Convert .txt file to .xls or .xlsx
我有來自 form.data 的數據,因此我將其轉換為 .txt 文件,因為在其中打開 Microsoft Excel 未完全加載它。 有超過 200 萬行。
出於這個原因,我決定嘗試使用 python 和以下腳本將 convert.txt 轉換為.xls 或.xlsx:
import csv
import openpyxl
input_file = 'path/to/inputfile.txt'
output_file = 'path/to/outputfile.xls'
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
with open(input_file, 'rb') as data:
reader = csv.reader(data, delimiter='\t')
for row in reader:
ws.append(row)
wb.save(output_file)
但我for row in reader: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
打開文件時,您必須在第二個參數中設置正確的模式。
使用rb
您以二進制模式打開它,但在這里您應該編寫r
以使用文本模式。
所以你的代碼應該是:
import csv
import openpyxl
input_file = 'path/to/inputfile.txt'
output_file = 'path/to/outputfile.xls'
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
with open(input_file, 'r') as data: # read in text mode
reader = csv.reader(data, delimiter='\t')
for row in reader:
ws.append(row)
wb.save(output_file)
正如評論中已經提到的,Excel 不適合這種數據量,因為它僅限於 1048576 行,但即使低於此數量,處理速度也會很慢。 您真的應該嘗試導入為 csv 或直接導入為 tsv。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.