Click here to Skip to main content
13,511,635 members
Rate this:
Please Sign up or sign in to vote.
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:")
            for row in teacherfileReader:
                  for field in row:
                        if field==teacher:


What I have tried:

Nearly works..

current output:

Enter teacher you are looking for:Mr A
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 17-Jul-17 5:37am
Updated 17-Jul-17 6:26am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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:
teacherfileReader = csv.reader(teacherfile, delimiter=':')

See also 14.1. csv — CSV File Reading and Writing — Python 3.6.2 documentation[^].
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.180417.1 | Last Updated 17 Jul 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100