1. 程式人生 > >學習python第一次應用---編寫登錄接口(關於while、if、for語句,dict以及文件的讀寫)

學習python第一次應用---編寫登錄接口(關於while、if、for語句,dict以及文件的讀寫)

char key 導致 結果 put orm nes while pen

  第一天看完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()


學習python第一次應用---編寫登錄接口(關於while、if、for語句,dict以及文件的讀寫)