简体   繁体   中英

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 :

 John, Password
 Mary, 12345
 Bob, myPassword

Usercheck.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 ','? 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. 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)

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.

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

I think that will help you to complet your programme. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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