目标:
编写可供用户查询的员工信息表
满足一下要求:
1.用户认证
2.员工信息表包括ID, Name, Department, Phone (contact_list.txt)
3.查询关键字:姓名
实战:
脚本内容
[codesyntax lang=”python”]
[root@Web-02 py]# cat contact_list.txt 1 Kobe IT 10000000001 2 Yao IT 10000000002 3 T-mac HR 10000000003 4 duncan HR 10000000004 5 robert OA 10000000005 6 john OA 10000000006 [root@Web-02 py]# cat contact_query.py #!/usr/bin/python while True: input = raw_input("Please input your username:") if input == 'alex': password = raw_input("Please input your passwd:") p = '123' while password != p: password =raw_input("Wrong passwd,Please input again:") else: print 'Welcome login to TRiAquae!\n' while True: match_yes = 0 input = raw_input("\033[32mPlease input the username you want to search:\033[0m") contact_file = file('contact_list.txt') while True: line = contact_file.readline() if len(line) == 0:break if input != ""and input in line: print 'Match item: \033[36;1m%s\033[0m' % line match_yes = 1 if match_yes == 0 :print 'No match item found' else: print "Sorry,user %s not found" % input
[/codesyntax]
脚本执行:
脚本注释:
#!/usr/bin/python
while True: #开启输入用户的循环
input = raw_input(“Please input your username:”) #定义一个变量用来存储输入的用户
if input == ‘alex’: #判断输入的用户名是否是alex,如果是alex,则让用户输入密码
password = raw_input(“Please input your passwd:”) #定义变量用来存储输入的密码
p = ‘123’ #定义用户的密码是123
while password != p:
password =raw_input(“Wrong passwd,Please input again:”) #当输入的密码不是123的时候,提示密码不正确,并且一直让用户输入密码
else:
print ‘Welcome login to TRiAquae!\n’? #当输入的密码是123的时候,提示欢迎信息
while True:?? #进入一个新的循环,用于判断用户输入的查找内容
match_yes = 0? #设置查找标记为0
input = raw_input(“\033[32mPlease input the username you want to search:\033[0m”) #定义变量用于存储用户的查找内容
contact_file = file(‘contact_list.txt’) #定义一个变量用来存储读取的文件内容
while True: #遍历文件内容
line = contact_file.readline() #定义变量存放读取文件的每一行内容
if len(line) == 0:break?? #判断文件是否读完,当行的长度为0时,文件已经读完了,则跳出遍历每行文件
if input != “” and input in line:
print ‘Match item: \033[36;1m%s\033[0m’ % line #如果输入的内容不为空,并且匹配到了某行,则打印这一行的内容
match_yes = 1 #设置查找到的标记为1
if match_yes == 0 :print ‘No match item found’ #如果没有匹配到,则打印没有内容找到
else:
print “Sorry,user %s not found” % input? #如果用户名不是alex,则打印用户名没有找到,并且一直让用户输入用户名