我正在尝试制作一个短信程序。 该程序要求您输入用户名和密码(并验证密码) 现在,登录后,您可以向其他人写入或读取您的文件(创建帐户后,程序将创建一个文本文件: .txt ,并在第一行保存密码)
如果您想在退出程序后登录,则可以,因为程序只需要知道是否存在包含您插入的用户名的 .txt 文件,并检查该文件的第一行以与输入进行比较(密码)。
问题是页面不清楚(我写信给该用户) 我无法登录。我什至打印了第一行,它与我的输入完全匹配。 问题是什么?
我的代码:(仅我读取第一行并与输入进行比较的部分)
with open(login_user+'.txt', 'r') as loginFile:
first_line = loginFile.readline()
loginFile.close()
while True:
login_password = raw_input('Password: ') # Taking password
if counter == 4:
print 'You failed 5 times, wait 30 seconds'
counter = 0
sleep(30)
elif login_password == first_line:
print '\nYou\'re connected to ' + login_user
break
else:
print(first_line)
print 'Incorrect password, Try again.'
counter += 1
提前非常感谢您!
最佳答案
首先,您不需要键入 loginFile.close()
,因为当使用 with
时,他就是处理它的人。
第二,修复 with
语句与后面两行之间的缩进。
第三,使用 rstrip为了删除行尾的空格,就像使用 raw_input
时一样,它不包含空格。
with open(login_user+'.txt', 'r') as loginFile:
first_line = loginFile.readline().rstrip()
string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, white-space characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
关于python - 写入文件后从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869979/