python的数据存储

Python存储数据

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

  1. 不管专注的是什么,程序都把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,你几乎总是要保存他们提供的信息;一种简单的方式是使用模块json来存储数据。

json(JavaScript object notation)格式最初是为JavaScript开发的,但随后成了一种常见的个是,被包括在Python在内的众多语言采用。

  1. 函数json.dump()接收两个实参:要存储的数据以及可用于存储数据的文件对象。
 import json  
 numbers =  [2,3,4,5,6]
 filename = 'numbers.json'
 with open(filename, 'w') as f_obj:
         json.dump(nuberms, f_obj)
  1. 函数json.load()将列表读取到内存
import json
filename = 'numbers.json'
with open(filename) as f_obj:
        numbers = json.load(f_obj)
print(numbers)

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

  1. 存储用户的名字
import json
username = input("what is your name?:")
filename = 'uasername.json'
with open(filename, 'w' ) as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back , "  + username + "!")
  1. 读取被存储的用户名
import json
filename = 'username.json'
with open(filename) as f_obj:
        username = json.load(f_obj)
        print("Welcome back, " + username + "!")
  1. 以前存储了用户名就加载它,否则就提示用户名并存储它
import json
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is 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_obj:
             username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_usename():
    """提示用户输入用户名"""
    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_usename()
         print("We'll remember you when you come back," + username  +  "!")


greet_user()

上述脚本实现了当username.json中存在用户名时获取问候,不存在用户名或者不存在这个文件时,重新获取用户名,并对新用户给出欢迎提示。

posted @ 2017-09-18 23:52  Federico  阅读(558)  评论(0编辑  收藏  举报