• 技术文章 >Python技术 >Python基础教程

    Python如何用json模块存储数据

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-07-01 09:56:17原创2595

    存储数据

    很多程序都要求用户输入某种信息,程序把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,就要保存提供的信息,一种简单的方式就是使用模块json来存储数据。

    模块json能将简单的python数据结构存储到文件中,并在程序再次运转时加载该文件中的数据。还可以使用json在python程序之间分享数据,与使用其他编程语言的人分享。

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

    1

    2

    3

    4

    5

    6

    7

    8

    import json

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

    filename = 'number.json'

    with open(filename, 'w') as f_ojb:  # 以写入模式打开文件

        json.dump(numbers, f_ojb)  # 使用函数json.dump()将列表存储到文件中

    with open(filename) as f_ojb:

        nums = json.load(f_ojb)  # 使用函数json.load()将这个列表读取到内存中

    print(nums)  # 打印读取到内存中的列表,比较是否与存入的列表相同

    运行结果:

    1

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

    相关推荐:《Python视频教程

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    import json

    # 存储用户的名字

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

    filename = 'username.json'

    with open(filename, 'w') as f_obj:

        json.dump(username, f_obj)  # 存储用户名与username.json文件中

        print("We'll remember you when you come back, " + username + "!")

    # 向名字被存储的用户发出问候

    with open(filename) as f_obj:

        un = json.load(f_obj)

        print("\nWelcome back, " + un + "!")

    运行结果:

    1

    2

    3

    What is your name? ela

    We'll remember you when you come back, ela!

    Welcome back, ela!

    优化上述代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    import json

    # 存储用户的名字

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

    filename = 'username.json'

    with open(filename, 'w') as f_obj:

        json.dump(username, f_obj)  # 存储用户名与username.json文件中

        print("We'll remember you when you come back, " + username + "!")

    # 向名字被存储的用户发出问候

    with open(filename) as f_obj:

        un = json.load(f_obj)

        print("\nWelcome back, " + un + "!")

    运行结果:

    1

    2

    3

    What is your name? ela

    We'll remember you when you come back, ela!

    Welcome back, ela!

    优化上述代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    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("\nWelcome back, " + username + "!")

    运行结果:

    1

    Welcome back, ela!

    3. 重构

    代码可以运行,但也可以做进一步改进——将代码划分成一些列完成具体工作的函数:这个过程称为重构。

    目的:让代码更清晰、易于理解、易扩展。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    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()

    专题推荐:python json 存储数据
    上一篇:Python sorted函数及用法 下一篇:Python如何传递任意数量的实参

    相关文章推荐

    • Python如何从文件中读取数据

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网