使用Python搜索文本文件中的列表

时间:2017-12-28 12:20:04

标签: python list text-files

我有一个注册帐户的程序,我现在正在处理一个记录所述帐户的功能。我已将列表“usernames”和“passwords”保​​存为单独的文本文件。

usernames = []
passwords = []
usernames.append(username)
passwords.append(password)

usernamesFile = open("usernames.txt","a")
for usernames in usernames:
    usernamesFile.write("%s\n" % usernames)
usernamesFile.close()

passwordsFile = open("passwords.txt", "a")
for passwords in passwords:
    passwordsFile.write("%s\n" % passwords)
passwordsFile.close()

while True:
    loginUsername = raw_input("Enter your username: ")
    usernamesFile = open("usernames.txt", "r")
    lines = usernamesFile.readlines() 
    if loginUsername in usernames:
        index = usernames.index(username)
        break
    else:
        print "Username not found"
        continue

我的问题是,即使我已经测试了文本文件并且它已经保存了我已经注册的所有用户名,搜索仍会返回“未找到用户名”。我不是Python方面的专家,所以如果你能以一种简单的方式解释那就太棒了!

2 个答案:

答案 0 :(得分:1)

您尚未在代码中使用lines读取usernames.txt文件来搜索其中的用户名。因此,请将代码修改为:

usernames = []
passwords = []
usernames.append(username)
passwords.append(password)

usernamesFile = open("usernames.txt","a")
for usernames in usernames:
    usernamesFile.write("%s\n" % usernames)
usernamesFile.close()

passwordsFile = open("passwords.txt", "a")
for passwords in passwords:
    passwordsFile.write("%s\n" % passwords)
passwordsFile.close()

while True:
    loginUsername = raw_input("Enter your username: ")
    usernamesFile = open("usernames.txt", "r")
    lines = usernamesFile.readlines() 
    if loginUsername in lines:
        index = lines.index(username)
        break
    else:
        print "Username not found"
        continue

答案 1 :(得分:0)

因为你是这样写的

usernamesFile.write("%s\n" % usernames)

"\n"添加到每个用户名的末尾,以便您的条件

if loginUsername in usernames:
除非您删除False或将其添加"\n"

,否则

始终为loginUsername