很多程序都要求用户输入某种信息,如让用户存储游戏首选项或提供要可视化的数据,程序都把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,可以使用模块json来存储数据。
Json模块提供了四个功能:dumps、dump、loads、load
例子一
1 #!/usr/bin/evn python 2 # -*- coding:utf-8 -*- 3 import json 4 numbers = [2, 5, 3, 7, 11, 13] 5 filename = "numbers.json" 6 with open(filename, "w") as f: 7 json.dump(numbers, f) 8 9 """ 10 json.dump(numbers, f)接受两个参数,存储数据和存储文件对像 11 """
1 #!/usr/bin/evn python 2 # -*- coding:utf-8 -*- 3 import json 4 filename = "numbers.json" 5 with open(filename) as f: 6 numbers = json.load(f) 7 print(numbers) 8 9 10 输入结果: 11 [2, 5, 3, 7, 11, 13]
例子二
1 #!/urs/bin/evn python 2 # -*- coding:utf-8 -*- 3 import json 4 # 如果以前存储了用户名,就加载它 5 # 否则,就提示用户名输入用户名并存储它 6 filename = "username.json" 7 try: 8 with open(filename) as f: 9 username = json.load(f) 10 except FileNotFoundError: 11 username = input("请输入用户名:") 12 with open(filename, "w") as f: 13 json.dump(username, f) 14 else: 15 print("welcome back" + " " + username)
1 #!/usr/bin/evn python 2 # -*-coding:utf-8 -*- 3 import json 4 data = { 5 "roles":[ 6 {"roles":"monster","type":"pig","life":50}, 7 {"roles":"hero","type":"关羽","life":80}, 8 ] 9 } 10 d = json.dumps(data) # 将数据类型转成字符串,序列化 11 print(d, type(d)) 12 d2 = json.loads(d) # 将字符串转成相应的数据类型,反序列化 13 print(d2["roles"], type(d2)) 14 15 16 输入结果: 17 {"roles": [{"roles": "monster", "type": "pig", "life": 50}, {"roles": "hero", "type": "u5173u7fbd", "life": 80}]} <class 'str'> 18 19 [{'roles': 'monster', 'type': 'pig', 'life': 50}, {'roles': 'hero', 'type': '关羽', 'life': 80}] <class 'dict'>