Python 使用文本文件创建登录系统
strong text我正在使用一个文本文件为基于python 3.7的简单文本游戏创建一个日志系统:Python 使用文本文件创建登录系统,python,python-3.x,Python,Python 3.x,strong text我正在使用一个文本文件为基于python 3.7的简单文本游戏创建一个日志系统: #puts information from a text file into a list so it can be compared to users inputs logininfo = [] for line in open('user input.txt'): separator = ':' line = line.split(separator) for v
#puts information from a text file into a list so it can be compared to users inputs
logininfo = []
for line in open('user input.txt'):
separator = ':'
line = line.split(separator)
for value in line:
logininfo.append(value)
#To see whats inside the list of 'logininfo'
print (logininfo)
#To separate it in the output screen, makes it easier too read
print("##########################")
username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))
#variable 'z' can be named anything
z = 0
#loops until it finds username in the database or goes through each data
while z < len(logininfo):
if username == str(logininfo[z]):
print ("Username exist")
#variable 'g' can be named anything or could: z = z+1
#one index higher than the usernames index (in the database) is always the corresponding password
g = z + 1
#puts data in new variable so we can remove the gaps it comes with it
passwordshouldequal = str(logininfo[g])
#Removes any spaces
passwordshouldequal.replace(" ", "")
#Checks information in the variable
print (passwordshouldequal)
if password == passwordshouldequal:
print("Entered")
exit()
else:
print ("password is wrong")
#so it does not exit the loop
exit()
z = z + 1
#if the username does not exist
print ("Error or username does not exist")
#将文本文件中的信息放入列表,以便与用户输入进行比较
logininfo=[]
对于打开的行('user input.txt'):
分隔符=':'
行=行。拆分(分隔符)
对于行中的值:
logininfo.append(值)
#查看“登录信息”列表中的内容
打印(登录信息)
#在输出屏幕中将其分开,使其更易于阅读
印刷品(印刷品)
username=str(输入(“请输入您的用户名:”)
password=str(输入(“请输入您的密码:”)
#变量“z”可以命名为任何名称
z=0
#循环,直到它在数据库中找到用户名或遍历每个数据
当z
预期结果以“Entered”结尾。实际结果以“password is Error”结尾。谁能帮帮我,谢谢
编辑:人们问我的“用户输入”文本文件中有什么内容,所以我拍了一张文本文件和输出屏幕的照片。同时感谢你们,我感谢你们所有人的帮助!用户输入(注册用户的用户名和密码)和输出屏幕的图片:
编辑#2:删除了末尾的else位,因为我忘了事先删除它(在修补代码时)
编辑#3:特别感谢迈克尔·理查森,他帮助我解决了我的问题。也特别感谢纳克,他超越了我,帮助我改进了我的代码。最后感谢所有对我的问题发表评论的人,你的每一条评论都已被阅读并铭记在心。所以,再一次n、 非常感谢!密码的结果应该是相等的。替换(“,”)未被存储。您需要将该行替换为:
passwordshouldequal = passwordshouldequal.replace(" ", "")
这可能仍然失败,因为最后一个用户名/密码可能包含新行字符(\n)。我将用以下字符替换它:
passwordshouldequal = passwordshouldequal.replace(" ", "").replace("\n", "")
或者更干净的方式:
passwordshouldequal = passwordshouldequal.strip()
首先,我建议用
和打开文件,这样文件将自动关闭,您不会在最后关闭文件。从字符串中删除空格的另一个更简单的方法是使用strip
方法,有3种类型的strip
方法,一种是从左侧删除(lstrip
)右侧的一个(rstrip
),常规的一个是两侧的移除(strip
)
还有一件事,谁是最后的else
条件?如果条件不在正确的行中,您的
你应该仔细检查你的代码,休息一下,想想你想要实现什么,不是吗。你能给你的文件“user input.txt”添加一个公共链接吗?到底是什么问题,以及最后的else
条件是谁?另外,你可以使用strip
方法删除空格。你是在增加z
1,它应该是2,因为您存储的是用户名+密码对。您没有在最后关闭文件。此代码存在多个问题,我强烈建议您学习更多Python,并进行一般编程。堆栈溢出是一个参考,而不是完整的指南或教程。
with open('user input.txt') as f:
for line in f:
# perform things with the file
# the file will closed automatically