我正在尝试使用Python中的pickle而且我失败了。对于我克服的每个错误,我得到另一个消息。我运行代码时收到以下消息。我使用'else'时出现语法错误。那是为什么?
我是Python的新手,但我无法弄清楚我做错了什么?
import pickle
def main():
file_mail = open('email.dat','wb')
save_data(file_mail)
file_mail.close()
def save_data(file):
email = {}
count = 0
while count == 0:
print('Add an email: 1')
print('Modify an email: 2')
print('Delete an email: 3')
print('Display the list: 4\n')
choice = input('Enter a number from the list above:')
if int(choice)== 1:
name = input('Name:')
mail = input('E-mail:')
email[name] = mail
print('Added Successfully')
if int(choice) == 2:
name = input('Name:')
mail = input('E-mail:')
email[name] = mail
print('Modified Successfully')
if int(choice) == 3:
name = input('Name:')
mail = input('E-mail:')
email[name] = mail
print('Deleted Successfully')
if int(choice) == 4:
print(email)
else:
print('Invalid selection')
c = input('Do you want to continue y/n: ')
if c.upper() == 'N':
count = 1
print('Invalid Letter')
file_mail = open('email.dat','wb')
pickle.dump(email,file_mail)
file_mail.close()
main()
答案 0 :(得分:3)
在阅读含有pickle的文件时尝试使用rb
模式:
file_mail = open('email.dat','rb')
email = pickle.load(file_mail)
在将obj的pickle表示写入打开的文件对象时使用wb
模式:
output = open('data.pkl', 'wb')
pickle.dump(data1, output)
查看pickle example的更多详情。
答案 1 :(得分:0)
谢谢@McGrady!这是我得到的最终答案。
import pickle
def main():
file_mail = open('email.dat','wb')
save_data(file_mail)
file_mail.close()
def save_data(file):
email = {}
count = 0
while count == 0:
print('Add an email: 1')
print('Modify an email: 2')
print('Delete an email: 3')
print('Display the list: 4\n')
choice = input('\nEnter a number from the list above:')
if int(choice)== 1:
name = input('Name:')
mail = input('E-mail:')
email[name] = mail
print('Added Successfully\n')
else:
if int(choice) == 2:
name = input('Name:')
mail = input('E-mail:')
if name in email:
email[name] = mail
print('Modified Successfully\n')
else:
print('Name not found')
else:
if int(choice) == 3:
name = input('Enter name you want to delete:')
if name in email:
email.pop(name)
print('Deleted Successfully\n')
else:
print('Name not found')
else:
if int(choice) == 4:
print(email)
else:
print('Invalid selection\n')
c = input('Do you want to continue y/n: ')
if c.upper() == 'N':
count = 1
else:
if c.upper() == 'N':
count = 1
print('Invalid Letter')
file_mail = open('email.dat','wb')
pickle.dump(email,file_mail)
file_mail.close()
main()