所以我试图创建一个可以搜索数据文件的代码:
这是我创建的代码:
def search():
option = input('Please select to search by \n1. Surname\n2. D.O.B\n')
if option == '1':
surname = input('Please enter surname: ')
while not surname.isalpha():
surname = str(input('Please enter a valid surname: '))
Myfile = open('Address book.csv', 'rt')
for line in Myfile:
if ',' + str(surname) + ',' in line:
print(line)
else:
print('No contacts found')
elif option == '2':
Validmonth = False
while Validmonth == False:
month = input('Please enter the birth month')
if month >='13' and month <='0':
print('Please enter a valid month')
else:
Validmonth = True
Myfile = open ('Address book.csv', 'rt')
for line in Myfile:
if str(month) in line:
print(line)
else:
print('No contacts found')
else:
print('Error, select a valid option')
search()
search()
我在尝试代码时不断得到这个结果:
Please select to search by
1. Surname
2. D.O.B
1
Please enter surname: Vickers
No contacts found
No contacts found
No contacts found
No contacts found
No contacts found
No contacts found
No contacts found
No contacts found
我想知道为什么?有人请帮帮忙吗?
答案 0 :(得分:1)
您在每一行上测试姓氏,然后为不匹配的每一行打印No contacts found
。
找到名称时突破循环,并使用else
套件代替for
循环:
for line in Myfile:
if ',' + str(surname) + ',' in line:
print(line)
break
else:
print('No contacts found')
else
循环上的 for
仅在您用尽可迭代时执行,因此当您不提前退出循环时。
你的姓氏是行上的第一个值,所以如果行以开头
,你最好测试一下:if line.startswith(surname + ','):
专业提示:阅读CSV文件时,请使用csv
module:
import csv
with open('Address book.csv', newline='') as myfile:
reader = csv.reader(myfile)
for row in reader:
if row[0] == surname:
print(row)
break
else:
print('No contacts found')