数据的组织维度
也称为数据的组织方式或存储方式,在python中常用的数据组织方式可分为一维数据、二维数据和高维数据。
一维数据:通常采用线性方式组织数据,一般使用列表、元组或集合进行存储数据。
二维数据:也称为表格数据,由行和列组成,使用二维列表进行存储。
高维数据:使用key-value方式进行组织数据,使用字典进行存储数据。python中内置的json模块专门用于处理JSON(javascript object Notation)格式的数据。
# 一维数据写入 def my_write(): lst = ['张三', '李四', '王五', '赵六'] with open('student.csv','w',encoding='utf-8') as file: file.write(','.join(lst)) # 一维数据读 def my_read(): with open('student.csv','r',encoding='utf-8') as file: s=file.read() print(s.split(',')) # 二维数据写入 def my_write_table(): lst=[ ['商品','单价','销量'], ['鼠标','50.5','30'], ['键盘','100','20'], ['显示器','830','50'] ] with open('商品销售.csv','w',encoding='utf-8') as file: for item in lst: file.write(','.join(item)) file.write('\n') # 二维数据读 def my_read_table(): l=[] with open('商品销售.csv','r',encoding='utf-8') as file: lst=file.readlines() for item in lst: s=item[:len(item)-1] l.append(s.split(',')) print(l) if __name__ == '__main__': # my_write() # my_read() my_write_table() my_read_table()
json模块的常用函数
| 函数名称 | 描述说明 |
| json.dumps(obj) | 将python数据类型转成JSON格式过程,编码过程 |
| json.loads(s) | 将JSON格式字符串转换成python数据类型,解码过程。 |
| json.dump(obj,file) | 与dumps()功能相同,将转换结果存储到文件file中 |
| json.load(file) | 与loads()功能相同,从文件file中读入数据 |
import json lst=[ {'name':'张三','age':18,'score':90}, {'name':'李四','age':19,'score':99}, {'name':'王五','age':17,'score':95} ] # list-->str s=json.dumps(lst,ensure_ascii=False,indent=4) # ensure_ascii=false 正常显示中文; indent增加缩进 print(type(s)) print(s) # str-->list lst2=json.loads(s) print(type(lst2)) print(lst2) # 将lst对象转换成json对象,并写入到文件红 with open('student.txt','w',encoding='utf-8') as file: json.dump(lst,file,ensure_ascii=False,indent=4) # 读取json数据 with open('student.txt','r',encoding='utf-8') as file: lst3=json.load(file) print(type(lst3)) print(lst3)
posted on
浙公网安备 33010602011771号