从csv文件导入和导出

时间:2013-05-02 18:20:45

标签: python csv python-3.x

enter image description here所以我试图创建一个可以搜索数据文件的代码:

  1. 通过姓氏检索并显示联系人的详细信息
  2. 按出生日期检索并显示所有具有特定月份生日的联系人。
  3. 这是我创建的代码:

    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
    

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

1 个答案:

答案 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')