python登录脚本_Python登录脚本;用户名和密码在单独的文件中

1586010002-jmsa.png

I'm looking for assistance to get my Python script to imitate a log-in feature while the credentials are stored in a separate file.

I got it to work from hard-coded Username and Password, and it also reads in a file, but I'm having some difficulty finding out how to link the two together.

Any assistance is appreciated.

The Python script is as follows:

print "Login Script"

import getpass

CorrectUsername = "Test"

CorrectPassword = "TestPW"

loop = 'true'

while (loop == 'true'):

username = raw_input("Please enter your username: ")

if (username == CorrectUsername):

loop1 = 'true'

while (loop1 == 'true'):

password = getpass.getpass("Please enter your password: ")

if (password == CorrectPassword):

print "Logged in successfully as " + username

loop = 'false'

loop1 = 'false'

else:

print "Password incorrect!"

else:

print "Username incorrect!"

I found this somewhere else that helped me read the file in, and it does print the contents of the text file, but I am unsure on how to progress from this:

with open('Usernames.txt', 'r') as f:

data = f.readlines()

#print data

for line in data:

words = line.split()

The text file contains the Usernames and Passwords in a format of: Test:TestPW Chris:ChrisPW Admin:AdminPW with each credential on a new line.

As I said previously, any help is appreciated!

Thanks.

解决方案

You could start having a dictionary of usernames and passwords:

credentials = {}

with open('Usernames.txt', 'r') as f:

for line in f:

user, pwd = line.strip().split(':')

credentials[user] = pwd

Then you have two easy tests:

username in credentials

will tell you if the username is in the credentials file (ie. if it's a key in the credentials dictionary)

And then:

credentials[username] == password

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值