如何在python中一次打印出一组信息



我是一个python初学者,我尝试制作一个联系人簿程序,但这就是问题所在,我想要添加类似搜索的功能,所以在我添加联系人姓名、电话号码、电子邮件和商店后它到另一个文件(contact.txt(我想访问它并通过搜索打印它。

示例:

姓名:Johan电话:036902480157电子邮件:Johan@Email.com

我想通过键入Johan的联系人姓名或电话号码来访问他所有的信息,我该怎么做?

注意:我想在的每一行打印姓名、电话号码和电子邮件

提前感谢

我的代码

import os
def head():
print("")
print("========================")
print("      Contact Book      ")
print("========================")
def restart():
response = input("nOpen menu again? (yes/no): ").lower()
if response == "yes":
task()
else:
print("nSee You next time!")
def task():
head()
done = False
print('''1. Add Contact
2. Search
3. View Contact List
4. Delete All Contact
5. Exit''')
while not done:
task = input("nWhat do You want to do? (1-5):")
if task == "1":
print("nAdding a new contact!")
with open('contact.txt', 'a') as f:
name = input("Name: ")
phone = input("Phone Number: ")
if not phone.isnumeric():
while not phone.isnumeric():
print("Invalid input, please enter only a number!")
phone = input("Phone Number: ")
email = input("Enter an email: ")
f.writelines(('n',('=' * 15),'nName: ',name,
'nPhone: ',phone,'nEmail: ',email,'n',('=' * 15)))
print("nContact is saved!")
done = True
restart()
elif task == "2":
with open('contact.txt', 'r') as f:
search = input("nSearch: ")
for i in f:
if search in i:
print(i)
else:
print("nNo info was found!")
done = True
restart()
elif task == "3":
if os.path.getsize('contact.txt') == 0:
print("nNo contact info available!")
else:
with open('contact.txt', 'r') as f:
print("nAll Contact Info")
for i in f:
print(i,end="")
done = True
restart()
elif task == "4":
with open('contact.txt', 'w') as f:
print("nSuccesfully deleted all contact info!")
done = True
restart()
elif task == "5":
print("See You next time!")
break
else:
print("Invalid input please enter a single number from 1 to 5")
restart()

task()

添加联系人,然后搜索此联系人打印:

Adding a new contact!
Name: mrd
Phone Number: 99
Enter an email: the@ff.com
Contact is saved!
...

What do You want to do? (1-5):2
Search: mrd
Name: mrd                  


No info was found!      

这是不准确的,因为你刚刚找到了这个名字。您要做的是将所有联系人信息保存在contacts.txt的同一行中,这样当您搜索数字名称时,它会返回该行,然后您可以根据需要打印它。

或者,您可以在内存中保存一个字典,按照建议在退出时将其保存在json中,并在启动程序时加载


回答评论

if task == "1":
print("nAdding a new contact!")
# TODO make sure no commas in the input!
name = input("Name: ")
phone = input("Phone Number: ")
while not phone.isnumeric():
print("Invalid input, please enter only a number!")
phone = input("Phone Number: ")
email = input("Enter an email: ")
with open('contact.txt', 'a') as f:
f.write(','.join([name, phone, email]) + 'n')
print("nContact is saved!")
done = True
restart()
elif task == "2":
search = input("nSearch: ")
with open('contact.txt', 'r') as f:
for i in f:
if search in i:
for caption, data in zip(['Name:', 'Phone:', 'Email:'],
i.split(',')):
print(caption, data)
break # contact was found don't go to the else!
else:
print("nNo info was found!")
done = True
restart()

最新更新