开发者

i have a list in my customer.txt how to create a search function to print out the whole customer information using python

Hi i have a list in my customer.txt file:

[1, 'Amin Milani Fard', 'Columbia College', 778]
[33, 'Ali Sulemanji', 'Langara College', 4324442211]
[32, 'Ali Sulemanji', 'Langara College', 4324442211]
[325, 'Ali Sulemanji', 'Langara College', 4324442211]
[2, 'Yuvin Ng','Dougles College',77839922003]
[3, 'Ali Sulemanji', 'Langara College', 4324442211]

my job is to create a search function that can track the customer name. for eg. type in the customer name:Yuvin Ng and it will return the whole list from Yuvin Ng's line

how can i do that? using python.

def search(n):
    name=input('Customer Name:')
    x=open('customerlist.txt','r')
    i=0
    while i<1000: # any开发者_Python百科way this is out of desperation to make the function work...
        z=x.readline()
        print(z)
        i+=1

im stuck... pleease help a.s.a.p thx you..


A simple approach would be to iterate over the lines in the file using in to check for a match, and if a match is found use eval to return the line as a list.

def search(file_name, name):
    with open(file_name) as f:
        for line in f:
            if name in line:
                return eval(line) 
    return []

>>> search('customer.txt', 'Yuvin Ng')
<<< [2, 'Yuvin Ng', 'Dougles College', 77839922003]


Think that you have to look at the pickle module. You code than will look the following way:

data = [[1, 'Amin Milani Fard', 'Columbia College', 778],
[33, 'Ali Sulemanji', 'Langara College', 4324442211],
[32, 'Ali Sulemanji', 'Langara College', 4324442211],
[325, 'Ali Sulemanji', 'Langara College', 4324442211],
[2, 'Yuvin Ng','Dougles College',77839922003],
[3, 'Ali Sulemanji', 'Langara College', 4324442211]]

import pickle

pickle.dump(data, open('c:\\file.txt','w'))

# than you can retrieve data the following way 

data = pickle.load(open('c:\\file.txt','r'))

# And now it is very easy to find data you need.
data[1]
>>> [33, 'Ali Sulemanji', 'Langara College', 4324442211]

# OR
for x in data:
   if 'Ali Sulemanji' in x:# or look for any other property/ies
        print x


Why not use a database instead of a flat file for storing the information? For example if you wanted to use a database called 'users', you could have something like

import _mysql
conn = _mysql.connect('localhost','root','','users')
with open(filename) as fp:
    for line in fp:
         then fill your query with the information like: 
         "..." % dict(zip([id,name,college,number],eval(line)))

Future queries can then be done with like

def search(name):
    cursor = conn.cursor()
    cursor.execute("Select * from users.users where name = %(name)"%locals())
    data = cursor.fetchone()
    cursor.close()
    return data
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜