试图创建一个火车预订系统。无法搜索我的 csv 并打印该特定行。
用户已经有 id 号,并且 csv 的设置如下
这是我到目前为止所拥有的:
You are matching the entire line against the ID. You need to split out the first field and check that:
def buySeat():
    id = raw_input("please enter your ID")
for line in open("customers.csv"):
    if line.split(',')[0] == id:
        print line
    else:
        print "sorry cant find you"
尝试使用内置的 CSV 模块。当您的需求发生变化时,它将使事情更容易管理。
import csv
id = raw_input("please enter your ID")
ID_INDEX = 0
with open('customers.csv', 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    for row in csvReader:
        # Ignore the column names on the first line.
        if row[ID_INDEX] != 'counter':
            if row[ID_INDEX] == id:
                print ' '.join(row)
            else:
                print 'sorry cant find you'