python读取txt文件为字典username_txt文件到字典和登录实现python3

您的基本问题是您的文件中有[ ]围绕用户名和密码组合,但您无法解释这一点。在

您的代码还有一些其他风格问题,以下是经过编辑的版本:import getpass

from time import sleep

password_file = r'C:\....\Database.txt'

def login(user,passwd):

''' Checks the credentials of a user '''

with open(password_file) as f:

for line in f:

if line.strip(): # skips blank lines

username,password = line.split(',') # this gets the individual parts

username = username[1:] # gets rid of the [

password = password[:-1] # the same for the password

if user == username and password == passwd:

return True

return False

if __name__ == '__main__':

username = input('Please enter the username: ')

passwd = getpass('Please enter the password: ')

if login(user,passwd):

print('Welcome {1}'.format(user))

sleep(3)

else:

print('Failed! Mwahahaha!!')

sleep(5)

首先,您不需要()来“初始化”变量;更重要的是在Python中根本不需要初始化变量。这是因为Python没有变量,而是有指向事物的名称。在

接下来,python style guide表示变量名和方法名应该是小写的。在

现在-代码的主要部分:

^{pr2}$

我使用split()将行分解为用户名和密码部分;但是正如您所见,[仍然把事情搞砸了。接下来我做了这个:>>> username[1:]

'username'

>>> password[:-1]

'sekret'

它使用slice notation来去除前导字符和结尾字符,去掉[ ]。在

这些线条:with open(password_file) as f: # 1

for line in f: # 2

if line.strip(): # skips blank lines

执行以下操作:{/ema>打开文件

这个for循环遍历f中的每一行,并为文件中的每一行指定名称line。

第三部分确保我们跳过空行。strip()将删除所有不可打印的字符;因此,如果没有剩余字符,则该行为空,并且将具有0长度。因为if循环只在条件为真时起作用,并且0是false value-实际上,我们只对非空行进行操作。

代码的最后一部分是另一个if语句。这是一个检查,以确保在从命令提示符执行文件时该文件将运行。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值