Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import csv #assuming the file is in csv format, import csv

#Task: Search for a teacher, and return the subject they teach
"""File contents
Mr A : Maths
Mr B: History
Mr C: Computing
"""

def main():
      #open the file
      with open("teacherbook1.csv", "r") as teacherfile:
            teacher=input("Enter teacher you are looking for:")
            teacherfileReader=csv.reader(teacherfile)
            for row in teacherfileReader:
                  for field in row:
                        if field==teacher:
                              print(row[1])
                              break
                        else:
                              main()



main()


What I have tried:

Nearly works..

current output:

Enter teacher you are looking for:Mr A
Philosophy
Enter teacher you are looking for:Mr B
Enter teacher you are looking for:Mr C
Enter teacher you are looking for:Mr X
Enter teacher you are looking for:
Posted
Updated 17-Jul-17 6:26am

The ':' character is not the default CSV field delimiter. If your file uses that, you have to specify it as parameter for the reader function:
PHP
teacherfileReader = csv.reader(teacherfile, delimiter=':')

See also 14.1. csv — CSV File Reading and Writing — Python 3.6.2 documentation[^].
 
Share this answer
 
You are restarting from the beginning if the teacher field is not the one requested. So if you enter "Mr B" or "Mr C" they will never be found. You need to remove the else statement and unindent the following line (main()) to the same level as the with statement at the beginning.
 
Share this answer
 
Comments
Ruth Benjamin Marvin 17-Jul-17 13:45pm    
Just wanted to check if codeproject operated in the same way with the same sort of response rate as stackoverflow - so far, impressed! Thanks!
Richard MacCutchan 17-Jul-17 15:45pm    
Sensible and informational questions tend to get the same type of answers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900