从.txt文件读取时如何检查两个字符串是否在同一行上

时间:2019-04-17 16:36:22

标签: python

我正在尝试制作一个记事本程序,您需要先登录才能阅读之前做的笔记。

在注册过程中,用户名保存在“ Passwords.txt”上的密码“ Usernames.txt”上。要验证用户名是否与密码匹配,我要检查特定用户名所在的行与用户名所在的密码所在的行相同。

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:2)

您可以打开两个文件并同时进行迭代:

with open('username.txt') as users, open('password.txt') as passwds:
    for user, passwd in zip(users, passwds):
        # Check username/password here

但是,这不是一个很好的存储布局。如果您在读取或写入文件时遇到任何错误,则身份验证数据库可能会损坏,并且一个用户可能会以另一个用户的密码结尾。

最好将两个属性都存储在一个文件中。可以使用JSON甚至CSV,但是最好使用内置的sqlite3模块。

答案 1 :(得分:0)

我不会在您的代码上发表评论,但我只会关注此方面:

  

我要检查某个用户名所在的行是否为   与用户名附带的密码所在的行相同   找到。

# Open the users file, read its content.
u = open("Usernames.txt","a+")
all_users = u.readlines()

# Compare each line with the username you are looking for.
user_to_find = "Sam"
line_where_user_was_found = None

for n,user in enumerate(all_users):
    if user == user_to_find:
        line_where_user_was_found = n
        break

# Open the passwords file, read its content.
p = open("Passwords.txt","a+")
all_passwords = p.readlines()

# Compare each lines with the password you are looking for.
password_to_find = "1234"
line_where_password_was_found = None

for m,password in enumerate(all_passwords):
    if password == password_to_find :
        line_where_password_was_found = m
        break

# Check if the username-password pair matches.
does_it_match = (line_where_user_was_found == line_where_password_was_found)

答案 2 :(得分:0)

您可以将文件的行读入列表:

with open("Usernames.txt") as f:
    usernames = f.readlines()

您可以使用index获取特定字符串的行号:

ix = usernames.index(username)

您当然可以通过将密码文件读入另一个列表并查看passwords[ix]来获得该索引处的密码。

答案 3 :(得分:0)

这应该为您带来想要的东西:

# Get login credentials from user and cast from unicode to string
username = str(raw_input("username:"))
password = str(raw_input("password:"))

# Get all valid usernames as a list and remove newlines from end
with open("Usernames.txt") as usernameFile:
    usernameList = [line.replace("\n", "") for line in usernameFile.readlines()]

# Get all valid passwords as a list and remove newlines from end
with open("Passwords.txt") as passwordFile:
    passwordList = [line.replace("\n", "") for line in passwordFile.readlines()]

# Figure out which lines the user's username and password are on
lineOfUsername = -2
lineOfPassword = -1
try:
    lineOfUsername = usernameList.index(username)
    lineOfPassword = passwordList.index(password)
# If either is not found, inform the user
except ValueError:
    print("Bad username or password")
    exit()

# If the lines match, then you got there!
if(lineOfUsername == lineOfPassword):
    # Your logic here
    print("Valid login")
# Otherwise, you didn't (womp, womp)
else:
    print("Bad username or password")

一些警告:

  • 这对安全性来说太可怕了。如上所示,这不是安全解决方案。如果您想知道为什么,请在YouTube的电脑爱好者上查找相关主题。
  • 如果用户名或密码都不正确,则不在此处说明。鉴于您提出的问题,真的不可能。

答案 4 :(得分:0)

检查此代码:

DWORD