python文件操作——保存、读取用户生成的数据

这篇博客介绍了如何使用Python的JSON模块来保存和读取用户生成的数据。通过json.dump()函数将数据写入.json文件,而json.load()函数则用于从文件中读取数据。示例代码展示了如何在没有找到已存储的用户名时提示用户输入并保存,以及在后续运行时欢迎回访用户。
摘要由CSDN通过智能技术生成

python文件操作——保存、读取用户生成的数据

JSON模块

模块json能够将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据,同时还可以使用jaon在python程序中分享数据。

函数json.dump() 和json.load()

函数json.dump() 接受两个参数:要储存的数据以及可用于存储数据的文件对象。如:

filename = 'aaa.json'
with open(filename, 'w') as f:
	json.dump(aaa, f)

函数json.load() 加载存储在 .json 文件中的信息。如:

filename = 'aaa.json'
with open(filename) as f:
	aaa = json.load(f)

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

import json

# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What's your name? ")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back, " + username + "!")
else:
    print("Welcome back, " + username + "!")

以上代码重构后:

import json


def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username


def get_new_username():
    """提示用户输入用户名"""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username


def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    if username:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")


greet_user()

运行结果

第一次运行结果:

What is your name? Alice
We'll remember you when you come back, Alice!

Process finished with exit code 0

第二次及多次的运行结果:

Welcome back, Alice!

Process finished with exit code 0

加油!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值