简体   繁体   English

搜索CSV并打印行

[英]searching a csv and printing a line

Trying to create a train booking system. 尝试创建火车预订系统。 Having trouble searching my csv and printing that certain line. 无法搜索我的csv并打印该特定行。

The user already has there id number,and the csv is is set out like 用户已经有ID号,并且csv设置为

This is what I have so far: 这是我到目前为止的内容:

You are matching the entire line against the ID. 您正在将整个行与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"

Try using the built-in CSV module. 尝试使用内置的CSV模块。 It will make things easier to manage as your requirements change. 随着需求的变化,这将使事情更易于管理。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM