python - importing and exporting from csv files -
so trying create code can search data file:
- by surname retrieve , display details contact
- by date of birth retrieve , display contacts birthday in particular month.
here code have created:
def search(): option = input('please select search \n1. surname\n2. d.o.b\n') if option == '1': surname = input('please enter surname: ') while not surname.isalpha(): surname = str(input('please enter valid surname: ')) myfile = open('address book.csv', 'rt') 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 birth month') if month >='13' , month <='0': print('please enter valid month') else: validmonth = true myfile = open ('address book.csv', 'rt') line in myfile: if str(month) in line: print(line) else: print('no contacts found') else: print('error, select valid option') search() search()
i keep getting result when try code:
please select search 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
i want know why? please help?
you test surname on every row, print no contacts found
every row doesn't match.
break out of loop when find name, , use else
suite for
loop instead:
for line in myfile: if ',' + str(surname) + ',' in line: print(line) break else: print('no contacts found')
else
on for
loop executed if exhausted iterable, when did not break out of loop early.
your surnames first value on line, better off testing if line starts surname:
if line.startswith(surname + ','):
pro tip: when reading csv files, use csv
module:
import csv open('address book.csv', newline='') myfile: reader = csv.reader(myfile) row in reader: if row[0] == surname: print(row) break else: print('no contacts found')
Comments
Post a Comment