【问题标题】:Comparing variables from file比较文件中的变量
【发布时间】:2017-03-29 12:52:55
【问题描述】:

脚本在python中,用于创建保存用户名和密码的文件,我知道整个脚本存在缺陷,但我想知道: 执行脚本时,用户名和密码将保存到以“,”分隔的文件中。每行都是一个新用户名的开始。调用登录功能时,将搜索列表并与输入的用户名进行比较,找到后是肯定的:检查密码,这是我的脚本无法按预期工作的地方。 为什么在比较 2 个变量(登录功能中的密码)时我不能得到肯定,它们应该是相同的。(注意 y,是从用户名和密码文件中读取的行,其中第一个元素是用户名和第二个密码)

def function():

    username=input('enter username')
    password=input('enter password')

    file=open('users1','a')
    file.write(username + ',' + password +'\n')


def login():

    user=input('username')
    passw=input('password')

    file=open('users','r')
    searchline=file.readline()

    for line in file:
        if user in line:
            x=line
            y=x.split(',')
            print(y[1])
            if user == y[1]:
                print('access confirmed')
            else:
                print('pass=', y[1])


function()

login()

【问题讨论】:

  • 你写和读的好像不是同一个文件
  • 另外,您将usery[1] 进行比较,这是第二个值(密码)
  • 您的问题是使用file.readline() - 字符串末尾有一个换行符,在其他版本的字符串中不会出现。使用:searchline = file.readline().rstrip().

标签: python


【解决方案1】:

您写入和读取的文件具有不同的名称(users1users)。从文件中读取的每一行都有一个行尾字符 (\n) 需要在比较密码之前将其删除。

def function():

        username = input('enter username')
        password = input('enter password')

        file = open('users','a')
        file.write(username + ',' + password + '\n')


def login():

        username = input('username')
        password = input('password')

        file = open('users','r')

        for line in file:
            if username in line:
                y = line.rstrip().split(',')
                print(y[1])
                if password == y[1]:
                    print('access confirmed')
                else:
                    print('password =', y[1])


function()

login()

查看rstrip上的python文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-07
    • 2014-01-27
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2017-07-15
    • 2014-03-09
    相关资源
    最近更新 更多