Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
txt文件到字典和登录实现Python 3_Python_Login_Dictionary - Fatal编程技术网

txt文件到字典和登录实现Python 3

txt文件到字典和登录实现Python 3,python,login,dictionary,Python,Login,Dictionary,我正在尝试创建登录脚本。我将用户名和密码保存在一个文本文件中,我希望python读取并检查该文件以查找用户名和密码 我遇到的最大问题是将密码“附加”到用户名。我目前只能扫描整个文档中的这两个部分,但不一定是相互附加的 #------------------------------------------------------------------------------- # Name: LogIn # Purpose: Logging In # # Author:

我正在尝试创建登录脚本。我将用户名和密码保存在一个文本文件中,我希望python读取并检查该文件以查找用户名和密码

我遇到的最大问题是将密码“附加”到用户名。我目前只能扫描整个文档中的这两个部分,但不一定是相互附加的

#-------------------------------------------------------------------------------
# Name:        LogIn
# Purpose:      Logging In
#
# Author:      Dark Ariel7
#
# Created:     19/02/2013
# Copyright:   (c) Dark Ariel7 2013
# Licence:     I take no responsability for anything.
#-------------------------------------------------------------------------------
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Username = ("")
Password = ()
def LogIn():
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
    Data = (Database.read())
    Username = ("")
    Password = ()
    Username = input("Username: ")
    Password = getpass(str("Password: "))
    LogIn= ",".join((Username,Password))
    if LogIn in Data:
        print("Welcome, " + Username)
        sleep(3)
        pass
    else:
        print("Failed, Sucker!")
        sleep(5)
        exit()

LogIn()
如果你们能帮我弄清楚
。加入
部分是为了什么,那就太好了。我应该制作一本字典并使用登录表的索引吗?我还需要一些关于如何使代码更好的一般性反馈

这是它将读取的txt文件:

[Dark Ariel7,123456]
[Poop,Anko]

*编辑抱歉,伙计们,我忘了提到我使用的是python 3而不是python 2。谢谢你。很快回复。同样,在最后一个else之后,我应该放什么来代替退出,这样函数才会循环,直到我得到正确的用户名密码组合?

您遇到的基本问题是,您的文件在用户名和密码组合周围有
[]
,但是您没有考虑到这一点

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

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没有变量;而是指向事物的名称

接下来,声明变量名应该是小写的,方法名也应该是小写的

现在-代码的主要部分:

>>> username, password = '[username,sekret]'.split(',')
>>> username
'[username'
>>> password
'sekret]'
我使用
split();但正如你所看到的,仍然有
[
把事情搞砸了。接下来我做了这个:

>>> username[1:]
'username'
>>> password[:-1]
'sekret'
这将使用删除前导字符和结尾字符,从而去掉
[]

这些线路:

   with open(password_file) as f: # 1
      for line in f: # 2
          if line.strip(): # skips blank lines
请执行以下操作:

  • 打开该文件并将其指定给变量f(请参阅中的详细信息)

  • 此for循环逐步遍历f中的每一行,并为文件中的每一行指定名称行

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

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

    该“.join”部分连接用户键入的用户名和密码,并在它们之间加上逗号(即Poop、Anko)因为这是它存储在数据库中的格式,所以您可以通过这种方式搜索它

    这是您的代码,经过了一些编辑,并对功能和样式进行了一些注释

    from getpass import getpass
    from time import sleep
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
    # These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces:  http://bytebaker.com/2008/07/30/python-namespaces/
    #Username = ("")
    #Password = ()
    def LogIn():
        Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
    #   Removed the parentheses; they have no effect here.  Putting parens around lone statements doesn't have any effect in python.
        Data = Database.read()
    #   These next two lines are pointless, because you subsequently overwrite the values you give these variables.  It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
    #   Username = ("")
    #   Password = ()
    #   Changed this from "input" to "raw_input" because input does something else that you don't want.
        Username = raw_input("Username: ")
        Password = getpass(str("Password: "))
        LogIn= ",".join((Username,Password))
        if LogIn in Data:
            print("Welcome, " + Username)
    #   Not sure why you want the script to sleep, but I assume you have your reasons?
            sleep(3)
    #   no need to pass
    #       pass
        else:
            print("Failed, Sucker!")
            sleep(5)
    #   exit() isn't necessary - the function will end by itself.
    #       exit()
    
    LogIn()
    

    抱歉,忘了提及我使用的是python 3。所有上述内容同样适用于python 3或2。我插入它进行测试,因为我不确定它到底是如何工作的,而且它也不工作。我认为这是因为您为python 2编写的。7抱歉,忘了提及我使用的是python 3