• Python中读取文件中的json串,并将其写入到Excel表格中


    Json:JavaScript Objective Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用语http请求中,,所以对json的学习也是自然而然的事情。

    有一个存着学生成绩的文件,文件中存的是json串,json串读起来特别不直观,写一个小程序,将它们写到excel表中,并计算出总分和平均分,json串格式如下:

    1 {
    2     "1":["小花",99,100,98.5],
    3     "2":["小王",90,30.5,95],
    4     "3":["小明",67.5,49.6,88]
    5 } 

    demo.py

     1 import json,xlwt
     2 def readExcel(file):
     3     with open(file,'r',encoding='utf8') as fr:
     4         data = json.load(fr) # 用json中的load方法,将json串转换成字典
     5     return data
     6 def writeM():
     7     a = readExcel('json')
     8     print(a)
     9     title = ["学号","姓名","语文成绩","数学成绩","英语成绩","总分","平均分"]
    10     book = xlwt.Workbook() # 创建一个excel对象
    11     sheet = book.add_sheet('Sheet1',cell_overwrite_ok=True) # 添加一个sheet页
    12     for i in range(len(title)): # 循环列
    13         sheet.write(0,i,title[i]) # 将title数组中的字段写入到0行i列中
    14     for line in a: # 循环字典
    15         print('line:',line)
    16         sheet.write(int(line),0,line) # 将line写入到第int(line)行,第0列中
    17         summ = a[line][1] + a[line][2] + a[line][3] # 成绩总分
    18         sheet.write(int(line),5,summ) # 总分
    19         sheet.write(int(line),6,summ/3) # 平均分
    20         for i in range(len(a[line])):
    21             sheet.write(int(line),i+1,a[line][i])
    22     book.save('demo.xls')
    23 
    24 if __name__ == '__main__':
    25     writeM()

    结果:

  • 相关阅读:
    spring ContextUtils
    mysql top slow sql my.cnf配置
    _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')
    linux Must my pidfile be located in /var/run? Stack Overflow
    zc.lockfile 1.0.0
    python Limit amount of RAM to a process (Linux) Server Fault
    使用 Nginx 提升网站访问速度
    bitnami mysql my.cnf配置
    Django pickling
    一个查找rpm包的站
  • 原文地址:https://www.cnblogs.com/xyf9575/p/7448613.html
Copyright © 2020-2023  润新知