zl程序教程

您现在的位置是:首页 >  Python

当前栏目

用Python做游戏系列:Python基础(import Json!)

2023-04-18 16:58:59 时间

很多程序都要求用户输入某种信息,如让用户存储游戏首选项或提供要可视化的数据。不管专注的是什么,程序都把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,你几乎总是要保存他们提供的信息;一种简单的方式是使用模块json来存储数据。

模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json在Python程序之间分享数据。更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。这是一种轻便格式,很有用,也易于学习。

首先,我们从简单的写起:

1import json
2number = [1,2,3,4,5,6]
3
4with open("E:\test_txt.txt",'w',encoding='utf-8') as file_object:
5    json.dump(number,file_object)

运行后文本文档中:

这样,我们完成了写入,那我们接下来来读取:

1import json
2#number = [1,2,3,4,5,6]
3
4with open("E:\test_txt.txt",'r',encoding='utf-8') as file_object:
5    number= json.load(file_object)
6
7print (number)

控制台打印:

当然,这也不算json,所以下面就是一个比较完整的json读取与解析:

1import json
2
3
4dict = {"name": "Tom", "age": 23}   
5data4 = json.dumps(dict)
6
7with open("E:\test_txt.json",'w',encoding='utf-8') as file_object:   
8    file_object.write(json.dumps(dict, indent=4))
9    json.dump(dict, file_object, indent=4)  

那么我们看生成的文件:

1{
2    "name": "Tom",
3    "age": 23
4}