需要安装xlwt库,可以用如下命令安装:
pip install xlwt
示例文本:
100 -494 td_error 0.6692215
200 318 td_error 0.57682794
300 57 td_error 0.45037615
400 260 td_error 0.42214713
500 586 td_error 0.45073098
600 615 td_error 0.4728373
700 731 td_error 0.48083866
800 802 td_error 0.3751492
900 440 td_error 0.4249844
1000 430 td_error 0.36427215
参考代码:
import xlwt
import codecs
input_txt = 'demo.txt'
output_excel = 'demo.xls'
sheetName = 'Sheet1'
start_row = 0
start_col = 0
wb = xlwt.Workbook(encoding = 'utf-8')
ws = wb.add_sheet(sheetName)
f = open(input_txt, encoding = 'utf-8')
row_excel = start_row
for line in f:
line = line.strip('\n')
line = line.split(' ')
print(line)
col_excel = start_col
len_line = len(line)
for j in range(len_line):
print (line[j])
ws.write(row_excel,col_excel,line[j])
col_excel += 1
wb.save(output_excel)
row_excel += 1
f.close