baker95935

这里的存储数据使用json格式

json   是javascript object notation的意思  javascript的对象标记

1 写入 json.dump

import json

numbers = [2, 3, 4, 5, 7, 11, 13]
filename = \'numbers.json\'
with open(filename, \'w\') as f_obj:
    json.dump(numbers,f_obj)

把列表中的数据 写入文件numbers.json

2 读取 json.load

import json
filename = \'numbers.json\'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)

把number.json中的数据 读取

 

最后看一个封装好的函数

import json
def get_stored_username():
    filename=\'username.json\'

    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    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_obj:
        json.dump(username, f_obj)
    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()

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2021-12-25
  • 2022-02-18
  • 2022-01-09
  • 2022-02-09
  • 2022-01-30
  • 2021-12-12
猜你喜欢
  • 2021-11-30
  • 2022-01-16
  • 2022-01-26
  • 2022-02-12
  • 2021-05-10
  • 2021-12-23
  • 2021-11-26
相关资源
相似解决方案