[英]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.