学习python第一次应用---编写登录接口(关于while、if、for语句,dict以及文件的读写)

  第一天看完python教学视频后,马上写了一小段代码,中间遇到了一些问题,想要马上记录下来,跟大家分享。

      编写登陆接口

  • 输入用户名密码
  • 认证成功后显示欢迎信息
  • 输错三次后锁定
1.使用dict进行读写文件(因为想用key,value的结构):
1)使用dict的格式写入文件中:
userfile = open("C:/Users/Administrator/PycharmProjects/untitled/day1/userdata.ini","w")

temp = {}
temp['name'] = "shelly"
temp['passwd'] = "123456"
userfile.write(str(temp)+ '\n')
temp['name'] = "Nancy"
temp['passwd'] = "234567"
userfile.write(str(temp) + '\n')
userfile.close()
2)使用dict的格式从文件中读取出来:
 
userfile = open("C:/Users/Administrator/PycharmProjects/untitled/day1/userdata.ini", "r")
lines = userfile.readlines()
for line in lines:
data = eval(line)
verifyData = False
if data['name'] == username and data['passwd'] == passwd:
print("welcome {_name} login ".format(_name = username))
userfile.close()
exit()

1.按行读取:
我将被锁定的名字记录到文件时,换行了,结果在匹配用户输入的名字,是否是被锁定的用户名,按行读取文件,进行匹配时,发现读取出来的值有换行符,导致判断有问题。
直接按行读取出来的数值会变成:shelly\n
解决方法:

data = line.split()[0]
这样读取出来的数据就会可以转化成想要的:shelly了。
 
我写的代码如下:

#coding=utf-8
import os
count = 3
while count > 0:
username = input("please input username:")
lockFile = open("C:/Users/Administrator/PycharmProjects/untitled/day1/lockList.cfg", "r")
lines = lockFile.readlines()
for line in lines:
if username == line.split()[0]:
print("Account is locked!!! ")
exit();
lockFile.close()
passwd = input("please input your passworld:")
userfile = open("C:/Users/Administrator/PycharmProjects/untitled/day1/userdata.ini", "r")
lines = userfile.readlines()
for line in lines:
data = eval(line)
verifyData = False
if data['name'] == username and data['passwd'] == passwd:
print("welcome {_name} login ".format(_name = username))
userfile.close()
exit()
count -= 1
if count > 0:
print("Your username or passworld is wrong!only have {_count} chance".format(_count = count))
else:
lockFile = open("C:/Users/Administrator/PycharmProjects/untitled/day1/lockLiat.cfg", "a")
lockFile.write(username+"\n")
lockFile.close()
print("Sorry,You have no chance!")
userfile.close()


猜你喜欢

转载自www.cnblogs.com/malimali/p/9175441.html
今日推荐