如何搜索csv文件并使缩进正确,这样可行 [英] How do I search a csv file and get the indentation right so this works

查看:127
本文介绍了如何搜索csv文件并使缩进正确,这样可行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

推荐答案

:字符不是默认的CSV字段分隔符。如果您的文件使用它,您必须将其指定为 reader 函数的参数:

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=':')



另请参见 14.1。 csv - CSV文件读取和写入 - Python 3.6.2文档 [ ^ ]。


如果教师字段不是请求的字段,则从头开始重新启动。因此,如果您输入B先生或C先生,他们将永远不会被发现。您需要删除 else 语句并取消以下行( main())与开头的语句。
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.


这篇关于如何搜索csv文件并使缩进正确,这样可行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆