如何在给定范围内从文件中进行更有效的匹配输入

时间:2017-10-19 17:18:29

标签: python file tkinter range itertools

我已经使用GUI创建了用户名和密码程序,我想确保如果用户输入任何正确的用户名或来自2个不同文件的任何正确密码,则显示“您已访问过某些内容”。但是,我不知道该怎么做,谢谢。目前它不起作用。这是我的计划的一部分:

def reveal(self):
    file=open('username.txt','r')
    data1=file.readlines()
    file.close

    file1=open('username.txt','r')
    data2=file1.readlines()
    file1.close

    content2=self.username.get()
    content=self.password.get()


    if content2==(data1[0,3].replace("\n","")) and content==(data2[0,3].replace("\n","")): 
        message='You have access to something special.'

    else:
        message='Access denied.'

    self.text.delete(0.0,END)
    self.text.insert(0.0,message)

我也试过这个,但它仍然不起作用:

def reveal(self):
    import itertools

    file1=open('username.txt','r')
    data1=file1.readlines()
    file1.close


    file=open('password.txt','r')
    data2=file.readlines()
    file.close

    content2=self.username.get()
    content=self.password.get()
    with open(username, "r") as file1 , open(password, "r") as file :
        if content2 ==itertools.islice(file1,0, 3) and content==itertools.islice(file,0, 3):

            message='you have access to something'


        else:
            message='Access denied.'

我希望这个程序能够使用每个文件中的多个用户名和密码,同时确保只有用户名文件中的数据[0]与密码文件中的data2 [0]匹配。

最新版本:

def reveal(self):
    file=open('username1.txt','r')
    data1 =file.read()
    file.close()

    file1=open('password1.txt','r')
    data2 =file1.read()
    file1.close()

    content2=self.username.get()
    content=self.password.get()


    data1 = data1.split("\n")
    data2 = data2.split("\n")
    for i in range(len(data1)):
        if data1[i] == content2 and data2[i] == content:
            message = 'You have access to something special.'
            break

        else:
            message='Access denied.'

    self.text.delete(0.0,END)
    self.text.insert(0.0,message)

1 个答案:

答案 0 :(得分:1)

我害怕我不明白你想要实现的目标

  

data1[0,3].replace("\n","")

  

(data2[0,3].replace("\n","")

如果我理解正确,每个文件中都有多个密码和用户名,任何密码都可以与任何用户名一起使用?

如果是这样,那么你想这样做:

if content2 in data1.split("\n") and content in data2.split("\n"):
    message = "You have access to something special."

请注意,您需要将file1.readlines()file.readlines()更改为file1.read()file.read()才能生效,或者只需将\n更改为每一行都有:

data1 = [i[:-1] for i in file.readlines()]

data2 = [i[:-1] for i in file1.readlines()]

编辑: 为了使它首先必须匹配第一个等,你可以这样做:

data1 = data1.split("\n")
data2 = data2.split("\n")
for i in range(len(data1)):
    if data1[i] == content2 and data2[i] == content:
        message = "You have access to something special."
        break