python - 使用用户输入将字典保存到文件
问题描述
我正在创建一个地址簿,您可以在其中添加/更新、搜索、显示地址和删除地址。我正在尝试将字典保存到文件中。
我曾尝试写入文件,但每次程序重置时,文件也会这样做。
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())
该文件保存字典,但如果您再次启动该程序,该文件将重置。
解决方案
两个问题。首先,您正在使用 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
推荐阅读
- php - PHP-FPM 没有从 Dockerfile 正确重启
- amazon-ec2 - 如何通过 AWS cloudfront 提供节点 js api?
- asp.net-mvc - 在索引视图上显示 ID 值而不是文本的静态下拉列表
- c# - Xamarin Forms 自定义控件 BindableProperty propertyChanged not Firing
- amazon-web-services - 如何保护 zappa `remote_env` 存储桶?
- kubernetes - 如何将 nodePort 映射到我自己定义的端口
- c++ - 如何在 Qt 中显示图片的颜色分量
- python - 处理“NatGatewayID”的正确属性是什么?
- ruby-on-rails - 如何在rails中使用相同的身份验证回调对两种类型的用户进行身份验证?
- java - OpenJDK 11 错误“无法初始化加密机制”