使用用户输入将字典保存到文件

时间:2019-06-07 19:02:04

标签: python file

我正在创建一个通讯簿,您可以在其中添加/更新,搜索,显示地址和删除地址。我正在尝试将字典保存到文件中。

我曾尝试写入文件,但是每次程序重置时,文件也是如此。

addressbook = {}
while(True):

    print('ADDRESS BOOK')
    print('-----------------------')
    print('-----------------------')
    print('1 - Add/Update contact')
    print('2 - Display all contacts')
    print('3 - Search')
    print('4 - Delete contact')
    print('5 - Quit')
    choice = input('')

    if choice == ('1'):
        addupdate = input('Do you want to add(1) or update(2) a contact?')
        if addupdate == ('1'):
            name = input('Enter the persons name:')
            address = input('Enter the address:')
            addressbook[name] = address
            print('Name added')
        elif addupdate == ('2'):
            thechange = input('''Who's address do you want to change?:''')
            newaddress = input('''What is the new address?:''')
            for key, value in addressbook.items():
                if key == thechange:
                    del addressbook[key]
                    addressbook[thechange] = newaddress
                    print('Address updated')
                    break

    elif choice == ('2'):
        for key, value in addressbook.items():
            print('Name:' + key)
            print('Address:' + value)
            print('--------')
    elif choice == ('3'):
        search_name = input('''Who's name do you want to search?:''')
        position = 0
        for key, value in addressbook.items():
            position = position + 1
            if key == search_name:
                print('Name %s found in %s position' % (search_name, position))
                break
            else:
                print('Name %s not found in %s position' %
                      (search_name, position))
    elif choice == ('4'):
        which_one = input('''Who's address do you want to delete?:''')
        for key, value in addressbook.items():
            if key == which_one:
                del addressbook[key]
                print('%s deleted' % which_one)
                break
            else:
                print('Name not found')
    elif choice == ('5'):
        addressfile = open('/home/robert/Addressbook.txt', 'w')
        addressfile.write(str(addressbook))
        addressfile.close
        break
addressfile = open('/home/robert/Addressbook.txt')
addressname = str(addressfile.read())

该文件保存了dict,但是如果再次启动该程序,则文件将重置。

1 个答案:

答案 0 :(得分:1)

两个问题。首先,您要使用代码w,这意味着您想使用a覆盖时要覆盖:

addressfile = open('/home/robert/Addressbook.txt', 'a')

第二,您没有关闭文件。您正在调用addressfile.close函数,但不是调用-因此,文件永远不会被保存,这就是为什么在运行文件后什么都没有显示。这样做:

addressfile.close()

或者,如果不想关闭文件,可以使用with,当您离开with块时,它会自动执行:

elif choice == '5':
    with open('/home/robert/Addressbook.txt', 'a') as addressfile:
        addressfile.write(str(addressbook))
    break