41.python shelve模块写入dat文件保存数据库

python shelve模块写入dat文件保存数据库

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import sys,shelve
def store_person(db):
    """
    存储信息
    :param db:
    """
    pid = input('Enter unique ID number:')
    person = {}
    person['name'] = input('Enter name:')
    person['age'] = input('enter age:')
    person['phone'] = input('enter phone nubmer:')
    db[pid] = person
def lookup_person(db):
    pid = input('enter ID number:')
    field = input('what would you like to know?(name,age,phone)')
    field = field.strip().lower()
    print(field.capitalize()+':',db[pid][field])
def print_help():
    print('The available commands are:')
    print('store:stores information about a person')
    print('lookup:Looks up a person from ID number')
    print('quit: Save changes and exit')
    print('?:Prints this message')
def enter_command():
    cmd = input('Enter_command (? for help):')
    cmd = cmd.strip().lower()
    return cmd
def main():
    database = shelve.open('D:\\database0103.dat')
    try:
        while True:
            cmd = enter_command()
            if cmd =='store':
                store_person(database)
            elif cmd =='lookup':
                lookup_person(database)
            elif cmd == '?':
                print_help()
            elif cmd == 'quit':
                return
    finally:
        database.close()


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    #print_hi('PyCharm')
    main()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

posted @ 2024-01-03 11:19  txwtech  阅读(25)  评论(0编辑  收藏  举报