Python查询CSV列
我正在用python创建一个菜单,但似乎无法在一个部分上运行它 我的代码从用户Python查询CSV列,python,csv,Python,Csv,我正在用python创建一个菜单,但似乎无法在一个部分上运行它 我的代码从用户raw\u输入中搜索邮政编码列 如果原始输入与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 Customer.
raw\u输入中搜索邮政编码列
如果原始输入
与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
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))
如果您真正想要的是在未找到匹配的邮政编码时退出,这应该会有所帮助。首先,找到一个匹配的邮政编码是一段很好的代码,它可以被提取并放入自己的函数中,如下所示。我不确定邮政编码是否是第三条记录,请根据需要更新记录常量
# 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
编写了匹配的_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名称通常仅用于类。这是代码的最后一部分,我需要类似else语句的内容,但只有当用户的输入等于CSV中的邮政编码时,才使用该记录。粘贴的内容中是否缺少一些import
语句?尝试在解释器中运行。是的,我现在已经添加了它们,如果您还需要什么,请告诉我?或通过Collabitt执行完整代码此代码未按提供的方式运行,它缺少一个函数readfile。但是我认为你的问题可以在没有所有支持代码的情况下得到回答,我将在下面尝试一下。