[英]Python: Writing emails and names into a Dict and File
I want to be able to write this without Pickling and I need to be able to save information from the Dict to the file and when I reload the program I can grab the info from the file.我希望能够在没有 Pickling 的情况下编写它,并且我需要能够将 Dict 中的信息保存到文件中,并且当我重新加载程序时,我可以从文件中获取信息。 Currently the code I have writes onto the file and can take from the dict but I cannot grab the info from the actual file itself.目前我已经写入文件的代码可以从字典中获取,但我无法从实际文件本身中获取信息。
Problem:问题:
Write a program that keeps names and email addresses in a dictionary as key-value pairs.编写一个程序,将名称和 email 地址作为键值对保存在字典中。 The program should display a menu that lets the user look up a person's email address, add a new name and email address, change an existing email address, and delete an existing name and email address. The program should display a menu that lets the user look up a person's email address, add a new name and email address, change an existing email address, and delete an existing name and email address. The program should save the data stored a dictionary to a file when the user exits the program.当用户退出程序时,程序应该将存储在字典中的数据保存到文件中。 Each time the program starts, it should retrieve the data from the file and store it in a dictionary.每次程序启动时,它应该从文件中检索数据并将其存储在字典中。
The Code I have:我拥有的代码:
#dictionary to store records
dictionary=dict()
def add_record(name, email):
dictionary[name]=email
save()
#saving values to file
def save():
with open('emails.txt', 'w') as handle:
handle.write(str(dictionary))
handle.close()
#looks up email for given name
def lookup_email(name):
read()
if name in dictionary.keys():
return dictionary[name]
#delets an email of given email
def delete_entry(name):
read()
if name in dictionary.keys():
dictionary[name]=None
del dictionary[name]
save()
return True
return False
#Menu display
def menu():
print("")
print("Menu")
print("-----------------------------------")
print("1. Look up an email address")
print("2. Add a new name and email address")
print("3. Change an existing email address")
print("4. Delete a name and email address")
print("5.Quit the program")
print("")
try:
selection=int(input("Enter your choice: "))
return selection
except:
print("Invalid Input")
#reads data from file
def read():
with open("emails.txt", "r") as file:
for line in file:
key, value = line.strip().split(",")
dictionary[key] = value
#Main function execution starts from here
if __name__ == '__main__':
while True:
choice=menu()
if choice==1:
name=input("Enter a name: ")
try:
email=lookup_email(name)
if(email!=None):
print(email)
else:
print("No Data Found")
except:
print("The specified name was not found")
elif choice==2:
name=input("Enter name: ")
email=input("Enter Email Address: ")
add_record(name, email)
print("Name and Email has been added")
elif choice==3:
name=input("Enter the Name: ")
email=input("Enter new Email Address")
add_record(name, email)
print("Information updated")
elif choice==4:
name=input("Enter the Name: ")
try:
delete_entry(name)
print("Information deleted")
except:
print("Something went wrong!!! please try again later")
elif choice==5:
save()
print("Information Saved")
break;
else:
print("invalid input")
You should not save your file like that (by converting the dictionary to a string then outputting it to a file) and rather should turn to other safe and commonly used solutions.您不应该那样保存文件(通过将字典转换为字符串然后将其输出到文件),而应该转向其他安全且常用的解决方案。 I'm not entirely sure why you would refuse to use pickle
, but json
is always another good substitute that works well with dictionaries.我不完全确定你为什么会拒绝使用pickle
,但json
始终是另一个很好的替代品,适用于字典。
from json import loads, dumps
# Saving
def save():
with open('emails.txt', 'w') as handle:
handle.write(dumps(dictionary))
handle.close()
# Loading
def load():
with open('emails.txt', 'w') as handle:
dictionary = loads(handle.read())
handle.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.