題目來自:Python 練習(xí)冊。題目1.8: 將純文本文件 student.txt為學(xué)生信息,,寫到 student.xls 文件內(nèi)。
查看更多于本人博客:iii.run
題目描述
題目1.8: 純文本文件 student.txt為學(xué)生信息, 里面的內(nèi)容(包括花括號)如下所示:
{
"1":["張三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
請將上述內(nèi)容寫到 student.xls 文件中,如下圖所示:

student.xls
這個題使用到文件讀取,數(shù)據(jù)讀取,Xls文件輸出三部分內(nèi)容。
文件讀取
使用open()函數(shù)
with open('student.txt') as f:
content = f.read()
數(shù)據(jù)讀取
d = json.loads(content)
xls文件輸出
file = xlwt.Workbook()
# 添加sheet
table = file.add_sheet('test')
for row, i in enumerate(list(d)):
table.write(row, 0, i)
for col, j in enumerate(d[i]):
table.write(row, col + 1, j)
file.save('student.xls')
參考代碼
student.txt 可以在這里下載~ http://cdn.mmmxcc.cn/blog/student.txt
#coding: utf-8
import os
import json
import xlwt
# 存放文件的目錄
filepath = 'D:'
os.chdir(filepath)
# 讀取文件內(nèi)容
with open('student.txt') as f:
content = f.read()
# 轉(zhuǎn)為json
d = json.loads(content)
file = xlwt.Workbook()
# 添加sheet
table = file.add_sheet('test')
for row, i in enumerate(list(d)):
table.write(row, 0, i)
for col, j in enumerate(d[i]):
table.write(row, col + 1, j)
file.save('student.xls')