1

在此处输入图像描述所以我正在尝试创建一个可以搜索数据文件的代码:

  1. 按姓氏检索和显示联系人的详细信息
  2. 按出生日期检索并显示特定月份生日的所有联系人。

这是我创建的代码:

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

我想知道为什么?有人请帮忙吗?

4

1 回答 1

1

您测试每一行的姓氏,然后打印No contacts found每一行不匹配的。

找到名称后跳出循环,并使用该else套件进行for循环:

for line in Myfile:
    if ',' + str(surname) + ',' in line:
        print(line)
        break
else:
    print('No contacts found')

elsefor仅当您用尽了可迭代对象时才会执行on a loop,因此当您没有提前退出循环时。

您的姓氏是该行的第一个值,因此最好测试该行是否以姓氏开头:

if line.startswith(surname + ','):

专业提示:读取 CSV 文件时,请使用csv模块

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')
于 2013-05-02T18:24:09.353 回答