Python编程_Lesson014_json和pickle模块讲解

json和pickle模块的使用

整个的文件结构图如下:
这里写图片描述

poedu_shop.py
import PoeduShop.user_operator


user_info_fp = "all_user_info.pickle"


def main():
    username = input("username:")
    password = input("password:")
    if PoeduShop.user_operator.user_login(username, password, user_info_fp):
        print("login success")
    else:
        print("login failed!")
        while True:
            print("""
        Please input:
        y: register a new user
        n: do not register
        """)
            user_input = input()
            if user_input == "y":
                username = input("username:")
                while username == "":
                    username = input("username:")
                password = input("password:")
                while password == "":
                    password = input("password:")
                salary = input("salary:")
                while salary == "":
                    salary = input("salary:")
                balance = input("balance:")
                while balance == "":
                    balance = input("balance:")
                if PoeduShop.user_operator.user_register(username, password, salary, balance, user_info_fp):
                    print("register success!")
                    break
                else:
                    print("register failed!")
            elif user_input == "n":
                break


if __name__ == "__main__":
    main()
else:
    print("Please Start The Progress from poedu_shop.py module!")

file_operator.py
import os.path


def __get_file_suffix(fp):
    """
    __get_file_suffix(fp)

    Get file suffix
    :param fp: file path
    :return:   return file suffix
    """
    return os.path.splitext(fp)[1]


def __get_module_info(fp):
    """
    __get_module_info(fp)

    Get file format
    :param fp: file path
    :return:   if the suffix either equals ".json" or equals ".pickle" return module info which
     includes module name, open and write mode, else return None
    """
    module_info = None
    suffix = __get_file_suffix(fp)
    if suffix == ".json":
        module_info = ["json", "r", "w"]
    elif suffix == ".pickle":
        module_info = ["pickle", "rb", "wb"]

    return module_info


def dump_file(list_data, fp):
    """
    dump_file(dict_data, fp)

    dump the dict_data to file with fp
    :param list_data: the data storage in the form of list
    :param fp: file path
    :return:   if storage success return True, else return False
    """
    return_value = True
    module_info = __get_module_info(fp)
    if module_info is None:
        return_value = False
        print("An unsupported file format")
    else:
        current_module = __import__(module_info[0])
        with open(fp, module_info[2]) as file:
            current_module.dump(list_data, file)

    return return_value


def load_file(fp):
    user_info_dict = None
    module_info = __get_module_info(fp)
    if module_info is None:
        print("An unsupported file format")
    else:
        current_module = __import__(module_info[0])
        try:
            with open(fp, module_info[1]) as file:
                user_info_dict = current_module.load(file)
        except Exception as e:
            print(e)

    return user_info_dict

user_operator.py
import PoeduShop.file_operator


all_user_info_list = []


def user_register(username, password, salary, balance, fp):
    """
    user_register(username, password, salary, balance)

    register a new user with user name, password, monthly salary and user balance.
    :param username:  User Name
    :param password:  Pass Word
    :param salary:    Monthly Salary
    :param balance:   User Balance
    :param fp:        file path
    :return:          return True if register success, else return False!
    """
    all_user_info_list.append({"username": username, "password": password, "salary": salary, "balance": balance})
    return PoeduShop.file_operator.dump_file(all_user_info_list, fp)


def user_login(username, password, fp):
    login_status = False
    user_info_list = PoeduShop.file_operator.load_file(fp)
    if user_info_list is not None:
        all_user_info_list.clear()
        for user_info in user_info_list:
            all_user_info_list.append(user_info)
            if username == user_info["username"] and password == user_info["password"]:
                login_status = True
                break

    return login_status


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值