当前位置: 首页 > 图灵资讯 > 行业资讯> Python如何用json模块存储数据

Python如何用json模块存储数据

发布时间:2025-10-30 16:17:41

存储数据

许多程序要求用户输入某些信息,并将用户提供的信息存储在列表、字典和其他数据结构中。当用户关闭程序时,保存提供的信息,一种简单的方法是使用模块json来存储数据。

模块json可以将简单的python数据结构存储在文件中,并在程序再次运行时加载文件中的数据。json还可以在python程序之间共享数据,并与使用其他编程语言的人共享。

1. 使用json.dump( )和json.load( )

importjson
numbers=[2,3,5,71,13]
filename='number.json'
withopen(filename,'w')asf_ojb:#以写入模式打开文件
json.dump(numbers,f_ojb)#使用函数json.dump()将列表存储在文件中
withopen(filename)asf_ojb:
nums=json.load(f_ojb)#使用函数json.load()将此列表读取到内存中
print(nums)#打印读取内存中的列表,比较是否与存储列表相同

运行结果:

[2,3,5,71,13]

相关推荐:Python视频教程

2. 保存和读取用户生成的数据

importjson
#存储用户名称
username=input('Whatisyourname?')
filename='username.json'
withopen(filename,'w')asf_obj:
json.dump(username,f_obj)#存储用户名和username.在json文件中
print("We'llrememberyouwhenyoucomeback,"+username+"!")
#问候存储在名称中的用户
withopen(filename)asf_obj:
un=json.load(f_obj)
print("\nWelcomeback,"+un+"!")

运行结果:

Whatisyourname?ela
We'llrememberyouwhenyoucomeback,ela!
Welcomeback,ela!

优化上述代码:

importjson
#存储用户名称
username=input('Whatisyourname?')
filename='username.json'
withopen(filename,'w')asf_obj:
json.dump(username,f_obj)#存储用户名和username.在json文件中
print("We'llrememberyouwhenyoucomeback,"+username+"!")
#问候存储在名称中的用户
withopen(filename)asf_obj:
un=json.load(f_obj)
print("\nWelcomeback,"+un+"!")

运行结果:

Whatisyourname?ela
We'llrememberyouwhenyoucomeback,ela!
Welcomeback,ela!

优化上述代码:

importjson
#存储用户名时加载,否则提示用户输入并存储
filename='username.json'
try:
withopen(filename)asf_obj:
username=json.load(f_obj)
exceptFileNotFoundError:
username=input('Whatisyourname?')
withopen(filename,'w')asf_obj:
json.dump(username,f_obj)
print("We'llrememberyouwhenyoucomeback,"+username+"!")
else:
print("\nWelcomeback,"+username+"!")

运行结果:

Welcomeback,ela!

3. 重构

代码可以运行,但也可以进一步改进——将代码分成一些列来完成特定工作的函数:这个过程称为重构。

目的:使代码更清晰、更容易理解和更容易扩展。

importjson
defget_stored_username():
"""如果存储用户名,则获取用户名"""
filename='username.json'
try:
withopen(filename)asf_obj:
username=json.load(f_obj)
exceptFileNotFoundError:
returnNone
else:
returnusername
defget_new_username():
"""提示用户输入用户名"""
username=input('Whatisyourname?')
filename="username.json"
withopen(filename,'w')asf_obj:
json.dump(username,f_obj)
returnusername
defgreet_user():
"""问候用户并指出他们的名字"""
username=get_stored_username()
ifusername:
print("Welcomeback,"+username+"!")
else:
username=get_new_username()
print("We'llrememberyouwhenyoucomeback,"+username+"!")
greet_user()

相关文章

Python如何用json模块存储数据

Python如何用json模块存储数据

2025-10-30
Python如何传递任意数量的实参

Python如何传递任意数量的实参

2025-10-30
Python中的返回值是什么

Python中的返回值是什么

2025-10-30
Python if else条件语句详解

Python if else条件语句详解

2025-10-30
Python pass语句及其作用

Python pass语句及其作用

2025-10-30
Python(for和while)循环嵌套及用法

Python(for和while)循环嵌套及用法

2025-10-30