Problem: 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示:
[
[1, 82, 65535],
[20, 90, 13],
[26, 809, 1024]
]
请将上述内容写到 numbers.xls 文件中,如下图所示:

Solution: Write Data to Excel III, Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import sys import json import xlsxwriter reload(sys) sys.setdefaultencoding('utf-8') def write_data_to_excel(f_path): ''' 把数据写入 xlsx 文件 ''' json_content = load_data_as_json(f_path) workbook = xlsxwriter.Workbook('numbers.xlsx') worsheet = workbook.add_worksheet('numbers') for i in xrange(len(json_content)): for j, item in enumerate(json_content[i]): worsheet.write(i, j, item) workbook.close() def load_data_as_json(f_path): ''' 将载入的 txt 文件转换成 json 数据格式 ''' with open(f_path, 'rb') as f: txt_content = f.read() return json.loads(txt_content) if __name__ == '__main__': f_path = 'numbers.txt' write_data_to_excel(f_path)
|
与 Exercise 0015: Write Data to Excel II 相似。
关于 JSON 语法,参考 JSON 语法。
题目来源:Python 练习册,每天一个小程序 THX!