一、存储数据到JSON文件
JSON是一种轻量级的文本数据交换格式,使用对象和数组的组合来表示数据。Python提供json库来实现JSON文件的读写操作。
JSON书写格式:键-值。{“name”:"CUYG"}
“键”是字符串(必须使用双引号,不能用单引号),“值”可以是字符串、对象、数组、数字、布尔值、null。
1、写入JSON文件
dumps()方法可以将Python数据类型转化成JSON格式字符串,调用write()方法写入文本。
原型:
dumps(obj,skipkeys=False,ensure_ascii=True,check_circular=True,allow_nan,cls=None,indent=None,sort_keys=False,**kw)
obj:Python数据序列;
skipkeys:是否跳过非Python基本类型的键;
ensure_ascii:显示格式,如果需要输出中文字符,需要将参数设置为False,并在写入文件时规定输出编码;
indent:输出时缩进字符个数;
sort_keys:是否根据键的值进行排序。
运行后出现student_info.json文件
文件内容出现中文乱码,可以加入
json.dumps(student_info,ensure_ascii=False)
结果为:
如果想要把内容变为以下格式:
可以在
json_info=json.dumps(student_info,indent=1,ensure_ascii=False)
#定义student_info
import json
student_info=[{'sna':'张三','age':22,'sex':'男'},
{'sna':'李四','age':21,'sex':'男'},
{'sna':'王五','age':23,'sex':'男'},
{'sna':'赵六','age':20,'sex':'男'}]
#把student_info转化为JSON格式,并赋值给json_info
json_info=json.dumps(student_info,indent=1,ensure_ascii=False)
print(json_info)
with open('student_info.json','w',encoding='utf-8') as file:
file.write(json_info)
2、读取JSON文件
利用loads()方法把JSON格式的字符串转化为Python数据类型,如果从JSON文件中读取内容,可以先调用文件的read()方法读取文本内容,在进行装换。
student_info.json文件内容如下:
新建text2.py文件,设置以下代码:
结果如图所示
#读取student_info.json文件
import json
with open('student_info.json','r',encoding='utf-8') as file:
#读取文件内容赋值个字符串 info
info=file.read()
print(info)
#把JSON格式字符串转化为Python数据类型
student_info = json.loads(info)
print("把JSON格式字符串转化为Python数据类型",student_info)
二、存储数据至CSV文件
字符风格符/逗号分隔符(CSV),其文件以纯文本形式存储表格数据。Python提供csv库实现CSV文件的读写操作。
1、写入CSV文件
csv库提供了初始化写入对象的writer()方法。
写入多行使用writerows()方法。
写入一行使用writerow()方法;
结果为:
注意:打开文件写入时,需要设置newline参数为‘’,否则每写入一行后将会写入一个空行。
2、读取CSV文件
读取CSV文件,可以通过调用reder()方法返回一个可迭代对象,次对象只能迭代一次。
运行结果
csv库还提供DictWriter()方法用于初始化一个字典写入对象,writeheader()方法用于写入表头,DictReader()方法用于把读取的数据转化为字典形式。