Python查询CSV列

时间:2014-04-08 18:56:47

标签: python csv

我正在python中创建一个菜单,似乎无法让它在一个部分工作。

我的代码会搜索用户raw_input的邮政编码列。

如果raw_input与customer.csv中的邮政编码不匹配,我希望代码只返回菜单

Customer.csv

1,Lee,test1,dy4zzz,121111111,3,4
2,luke,test2,dy5xxx,854539116,5,6
3,alex,test3,dy1ttt,7894561230,9,8
4,aaron,test4,b65yyy,16464634676974,8,9

来自程序的代码

import csv,os,time,math

def menu():
    print (""" Main Menu
        1.Add New Route
        2.Add Customer
        3.Edit Customer
        4.View Customer
        5.Exit """)
    ch=raw_input("Enter your choice")
    if ch=="1":
        NewRoute("Route.csv")
    elif ch=="2":
        cid=readfile("customer.csv")
        addtofile("customer.csv", cid)
        menu()
    elif ch=="3":
        editrecord("customer.csv")
        os.remove("customer.csv")
        os.rename("temp.csv","customer.csv")
        menu()
    elif ch=="4":
        readfile("customer.csv")
        menu()
    elif ch=="5":
        exit()
    elif ch !="":
        print ("try again")
        menu()



def NewRoute(file_name):
    print "Route Calculator"
    f=open("route.csv","w")#Opens Route file for writing
    f.truncate() #clears all contents from file so a new route can be written to it
    f.close() #saves and closes route file 
    driver=raw_input("Enter Drivers Name: ")
    readfile("customer.csv")
    cur = (0, 0)
    route = [0]
    xy = [ ]
    z= ()
    zz= []
    n = input("Please input the amount of destinations you want to visit:")
    a = range(1, n + 1)
    cidd = []
    record = [1]
    for i in range(n):
        cid=raw_input("Enter Postcode with no spaces and in lowercase:")
        f3=csv.reader(open("customer.csv",'r'))


        for row in f3:
            if row[3]==cid:
                x=eval(row[5])
                y=eval(row[6])
                z=row[1]
                xy.append((x,y))
                zz.append(((cid,z)))
                cidd.append((cid,z))

1 个答案:

答案 0 :(得分:1)

如果找不到匹配的postcode,如果您真正想要退出,这应该有所帮助。首先,找到匹配的邮政编码是一个很好的代码,可以提取并放置在它自己的功能,如下所示。我不确定邮政编码是否是第3条记录,必要时更新REC_常数。

# Constants for accessing your CSV record (up to postcode)
REC_NUM = 0
REC_NAME = 1
REC_FIELD3 = 2
REC_POSTCODE = 3


def matching_postcode_row(post_code):
    reader = csv.reader(open('customer.csv'))
    for rec in reader:
        if post_code == rec[REC_POSTCODE]:
            return rec
    return None

写入matching_postcode_row函数后,您现在可以这样调用它:

cid=raw_input("Enter Postcode with no spaces and in lowercase:")
rec = matching_postcode_row(cid)
if not rec:
    return

作为一种风格问题,您应该将NewRoute重命名为new_route。 CamelCased名称通常仅用于类。