这里的存储数据使用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()