【py coding everyday】2023-02-09

存储数据
模块json可以将简单的Python数据转存到文件中,并在程序再次运行时加载该文件的数据

json = JavaScript object notation

使用json.dump :
函数json.dump接受两个实参,要存储的数据,以及可用于存储数据的文件对象。
演示如下:

import json

numbers = [2,3,5,7,11,13]

filename = 'text_files/numbers.json'
with open(filename,'w') as f:
    json.dump(numbers,f)

会在指定的文件夹中新建这个numbers.json的文件,打开后

[2, 3, 5, 7, 11, 13]

再编写程序,使用json.load() 将列表读取到内存中

filename = 'text_files/numbers.json'
with open(filename) as f:
    numbers = json.load(f)

print(numbers)
[2, 3, 5, 7, 11, 13]
[Finished in 78ms]

存储用户的名字:

import json

username = input("What is your name? ")

filename = 'text_files/username.json'
with open(filename,'w') as f:
    json.dump(username,f)
    print(f"We'll remenber you when you come back, {username}")

打开json文件后是如此内容

"melong"

再来编写另一个程序,向已存储了名字的用户发出问候:

import json
filename = 'text_files/username.json'
with open(filename) as f:
    username = json.load(f)
    print(f"Welcome back, {username}")

执行之后

Welcome back, melong
[Finished in 62ms]

将上述两个程序合并,变成“组合拳”
编写一个尝试恢复用户名的try代码块。如果文件不存在,就在except代码块中提示用户输入用户名,并将其存储在username.json文件中,再次运行时可以

import json 

filename = 'text_files/username.json'
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename, 'w') as f:
        json.dump(username,f)
        print(f"We'll remember you when you come back, {username}!")
else:
    print(f"Welcome back, {username}! ")

第一次执行结果

X:\Python\Python38\python.exe X:\python_work\test.py 
What is your name? xiaoming
We'll remember you when you come back, xiaoming!

Process finished with exit code 0

第二次及以后执行都显示

X:\Python\Python38\python.exe X:\python_work\test.py 
Welcome back, xiaoming! 

Process finished with exit code 0

尝试打开username.json,因为不存在,所以先在except中创建,引发了FileNotFoundError,创建了用户后,再次执行就是
第二次的结果

重构:
将代码通过将一些列完成具体工作的函数,进行改进并实现,称之为重构
让代码更清晰、易于理解、容易扩展

import json
def greet_user():
    """问候用户,并指出其名字"""
    filename = 'text_files/username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        username = input("What is your name? ")
        with open(filename,'w') as f:
            json.dump(username,f)
            print(f"We'll remember you when you come back,{username}")
    else:
        print(f"Welcome back, {username}!")
greet_user()

执行之后,由于上述文件及内容存在,所以结论是

Welcome back, xiaoming!
[Finished in 62ms]

将获取已存储用户名的代码转移到另一个函数中,减少greet_user的任务量

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

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username}")
    else:
        username = input("What is your name? ")
        filename = 'text_files/username.json'
        with open(filename,'w') as f:
            json.dump(username, f)
            print(f"We'll remember you when you come back, {username}")
greet_user()

如果文件username.json不存在,就返回None,这让我们能够使用函数的返回值做简单的测试。
如果成功地获取了用户名,就打印一条欢迎用户回来的消息,否则提示用户输入用户名。
再重构greet_user()中的另一个代码块

import json
def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'text_files/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 = 'text_files/username.json'
    with open(filename,'w') as f:
        json.dump(username,f)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username}")
    else:
        username = get_new_username
        filename = 'text_files/username.json'
        print(f"We'll remember you when you come back, {username}")

greet_user()

在这个最终版本中,每个函数都执行单一而清晰的任务

最后在必要时调用get_new_username() ,
该函数只负责获取并存储新用户的用户名。要编写出清晰而易于维
护和扩展的代码,这种划分必不可少。

[2023-05-31 11:07:02] Started by user coding [2023-05-31 11:07:02] Running in Durability level: MAX_SURVIVABILITY [2023-05-31 11:07:04] [Pipeline] Start of Pipeline [2023-05-31 11:07:06] [Pipeline] getContext [2023-05-31 11:07:07] [Pipeline] node [2023-05-31 11:07:07] Running on Jenkins in /root/codingci/tools/jenkins_home/workspace/2553946-cci-31810232-464995 [2023-05-31 11:07:07] [Pipeline] { [2023-05-31 11:07:08] [Pipeline] withEnv [2023-05-31 11:07:08] [Pipeline] { [2023-05-31 11:07:08] [Pipeline] withDockerRegistry [2023-05-31 11:07:08] [Pipeline] { [2023-05-31 11:07:08] [Pipeline] isUnix [2023-05-31 11:07:08] [Pipeline] sh [2023-05-31 11:07:08] + docker inspect -f . public/docker/nodejs:18-2022 [2023-05-31 11:07:08] /root/codingci/tools/jenkins_home/workspace/2553946-cci-31810232-464995@tmp/durable-221f7a67/script.sh: 1: docker: not found [2023-05-31 11:07:08] [Pipeline] isUnix [2023-05-31 11:07:08] [Pipeline] sh [2023-05-31 11:07:09] + docker inspect -f . coding-public-docker.pkg.coding.net/public/docker/nodejs:18-2022 [2023-05-31 11:07:09] /root/codingci/tools/jenkins_home/workspace/2553946-cci-31810232-464995@tmp/durable-4892b310/script.sh: 1: docker: not found [2023-05-31 11:07:09] [Pipeline] isUnix [2023-05-31 11:07:09] [Pipeline] sh [2023-05-31 11:07:09] + docker pull coding-public-docker.pkg.coding.net/public/docker/nodejs:18-2022 [2023-05-31 11:07:09] /root/codingci/tools/jenkins_home/workspace/2553946-cci-31810232-464995@tmp/durable-0770ad1b/script.sh: 1: docker: not found [2023-05-31 11:07:09] [Pipeline] } [2023-05-31 11:07:09] [Pipeline] // withDockerRegistry [2023-05-31 11:07:09] [Pipeline] } [2023-05-31 11:07:09] [Pipeline] // withEnv [2023-05-31 11:07:09] [Pipeline] } [2023-05-31 11:07:09] [Pipeline] // node [2023-05-31 11:07:09] [Pipeline] End of Pipeline [2023-05-31 11:07:09] ERROR: script returned exit code 127 [2023-05-31 11:07:09] Finished: FAILURE
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值