![](/img/trans.png)
[英]Getting Python to read the next line in a text file after user inputs Y to continue
[英]Python 3: Getting two user inputs from a single line in a text file
我正在开发一个程序,要求用户输入用户名和密码,该程序检查用户名和密码是否在文本文件中。 如果用户名和密码不在文本文件中,它会询问用户是否要创建新用户。 如果用户名和密码与文本文件中的匹配,则拒绝用户输入。 如果成功,用户名和密码将保存到文本文件中,另起一行(用户名和密码用逗号分隔)。
文本.txt :
John, Password
Mary, 12345
Bob, myPassword
用户检查.py:
input: John
# Checks if 'John' in text.txt
input2: Password
# Checks if 'Password' in text.txt
output: Hello John! # If both 'John' and 'Password' in text.txt
input: Amy
# Checks if 'Amy' in text.txt
input2: passWoRD
# Checks if 'passWoRD' in text.txt
output: User does not exist! # If 'Amy' and 'passWoRD' not in text.txt
output2: Would you like to create a new user?
# If 'yes'
output3: What will be your username?
input3: Amy
# Checks if 'Amy' in text.txt
output4: What will be your password?
input4: passWoRD
# Adds 'Amy, passWoRD' to a new line in text.txt
我如何检查文本文件 text.txt 中以“,”分隔的用户名和密码,而不需要用户输入“,”? 并且还能够创建一个新的用户名和密码(用“,”分隔),将其添加到文本文件中?
您可能知道open()
函数。 使用此功能,您可以打开这样的文件:
open('text.txt', 'a')
参数 1 是文件,参数 2 是模式(r 表示只读,w 表示只写,a 表示两者和附加)
所以要逐行读取打开的文件:
file = open('text.txt', 'a')
lines = file.readlines()
for line in lines:
name, pass = line.split(',')
if name == 'whatever':
#...
最后写入文件你有write()
函数。
file.write(name + ',' + pass)
我认为这将有助于您完成您的计划。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.