简体   繁体   English

Python 3:从文本文件中的一行获取两个用户输入

[英]Python 3: Getting two user inputs from a single line in a text file

I am working on a program that asks the user to enter a username and password and the program checks if the username and password is in the text file.我正在开发一个程序,要求用户输入用户名和密码,该程序检查用户名和密码是否在文本文件中。 If the username and password is not in the text file, it asks if the user wants to create a new user.如果用户名和密码不在文本文件中,它会询问用户是否要创建新用户。 If the username and password matches one in the text file, it rejects the user input.如果用户名和密码与文本文件中的匹配,则拒绝用户输入。 If it is successful, the username and password is saved to the text file, on a new line (the username and password separated by a comma).如果成功,用户名和密码将保存到文本文件中,另起一行(用户名和密码用逗号分隔)。

text.txt :文本.txt :

 John, Password
 Mary, 12345
 Bob, myPassword

Usercheck.py :用户检查.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

How could I check the text file text.txt for a username AND password that is separated by a ',' without the user entering a ','?我如何检查文本文件 text.txt 中以“,”分隔的用户名和密码,而不需要用户输入“,”? And also be able to create a new username and password (which is separated by a ','), adding it to the text file?并且还能够创建一个新的用户名和密码(用“,”分隔),将其添加到文本文件中?

You may know the open() function.您可能知道open()函数。 With this function you can open a file like this:使用此功能,您可以打开这样的文件:

open('text.txt', 'a')

Parameter 1 is the file and parameter 2 is the mode (r for read only, w for write only and a for both and appending)参数 1 是文件,参数 2 是模式(r 表示只读,w 表示只写,a 表示两者和附加)

So to read the open file line by line :所以要逐行读取打开的文件:

file = open('text.txt', 'a')
lines = file.readlines()
for line in lines:
    name, pass = line.split(',')
    if name == 'whatever':
    #...

And finally to write to the file you've got the write() function.最后写入文件你有write()函数。

file.write(name + ',' + pass)

I think that will help you to complet your programme.我认为这将有助于您完成您的计划。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM