首页 > 解决方案 > 使用用户输入将字典保存到文件

问题描述

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

我曾尝试写入文件,但每次程序重置时,文件也会这样做。

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

该文件保存字典,但如果您再次启动该程序,该文件将重置。

标签: pythonfile

解决方案


两个问题。首先,您正在使用 code 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

推荐阅读