该程序必须是一本简单的通讯录,其中包含姓名,电话号码和电子邮件。您需要能够搜索人员并添加联系人。我得到了以足够好的方式保存到文本文件的程序,并试图逐行搜索文件。如果它具有搜索到的名称,我可以将其打印出来,但是我无法弄清楚如何让该程序告诉您是否根本找不到联系人。用我有我的代码的当前方式,该名称不在的每一行都会显示“ Contact Not Found”。如果该名称不在文本文件中,我怎么会只说一次未找到?
我尝试过的是:
f = open('contacts.txt', 'a')
def make_contact(name, phone, email):
f = open('contacts.txt', 'a')
f.write('\n' + 'Name: ' + name + ' Phone: ' + phone + ' Email: ' + email)
f.close()
menu_input = 0
while menu_input != 3:
print('\n1. Search Contact\n2. Add Contact\n3. Exit')
menu_input = int(input("\nChoose Option: "))
if menu_input == 1:
name = input ('\nEnter a Name to Search: ')
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
else:
print("\nContact Not Found!")
f.close()
elif menu_input == 2:
f = open('contacts.txt', 'a')
name = input("Enter Name: ")
phone = input("Enter Phone Number: ")
email = input("Enter Email: ")
make_contact(name, phone, email)
我将添加一个新的联系人,说Timmy,当我搜索Timmy时,在到达Timmy之前,每行都会说“ Not Found”。对于Timmys联络人行之前的所有联络人,它会重复“ Not Found”
答案 0 :(得分:2)
使用for-else
更改这部分代码。
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
break
else:
print("\nContact Not Found!")
它将通过if
循环检查for
条件,如果有匹配项,它将打印该行并从循环中退出。如果迭代结束且未找到匹配项,它将检查与else
循环并行的for
条件。
如果您要打印所有重复的记录,请保留一个匹配标志
flag = False
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
print("\n" + line)
flag = True
if not flag:
print("\nContact Not Found!")
答案 1 :(得分:0)
您可以在代码中添加一个简单的标志,以确定是否找到了它。实现是这样的:
with open('contacts.txt', 'r') as searchfile:
found=False
for line in searchfile:
if name in line:
print("\n" + line)
found = True
if not found:
print("\nContact Not Found!")
答案 2 :(得分:0)
您可以在搜索循环中添加标志。一旦发现,就可以打破循环。
f = open('contacts.txt', 'a')
def make_contact(name, phone, email):
f = open('contacts.txt', 'a')
f.write('\n' + 'Name: ' + name + ' Phone: ' + phone + ' Email: ' + email)
f.close()
menu_input = 0
while menu_input != 3:
print('\n1. Search Contact\n2. Add Contact\n3. Exit')
menu_input = int(input("\nChoose Option: "))
if menu_input == 1:
flag = False
name = input ('\nEnter a Name to Search: ')
with open('contacts.txt', 'r') as searchfile:
for line in searchfile:
if name in line:
flag = True # here you add flag
print("\n" + line)
break
if not flag:
print("\nContact Not Found!")
f.close()
elif menu_input == 2:
f = open('contacts.txt', 'a')
name = input("Enter Name: ")
phone = input("Enter Phone Number: ")
email = input("Enter Email: ")
make_contact(name, phone, email)