python小程序-0012

第12题:纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:

{
“1”:[“张三”,150,120,100],
“2”:[“李四”,90,99,95],
“3”:[“王五”,60,66,68]
}
请将上述内容写到 student.xls 文件中,如下图所示:
python小程序-0012_第1张图片

#!/usr/bin/env python3
# -*- coding : utf-8 -*-

import xlwt
import json
from collections import OrderedDict


def txt_xls_student(txtpath):
    with open(txtpath,'r') as f:
        txtdata = json.load(f,object_pairs_hook = OrderedDict)
    workbook = xlwt.Workbook()
    sheet1 = workbook.add_sheet('student',cell_overwrite_ok = True)
    for index,(key,values) in enumerate(txtdata.items()):
        #print(key,values)
        sheet1.write(index,0,key)
        for i,value in enumerate(values):
            sheet1.write(index,i + 1,value)
    workbook.save('student.xls')


if __name__ == '__main__':
    txtpath = input('Please input txt file path: ')
    txt_xls_student(txtpath)

你可能感兴趣的:(python,python)