我想知道如何将文本文件的多行与单个变量进行比较。我已经使其部分工作了,但它只能与文本文件的最后一行进行比较
def loginSetup():
global loginSelector
global accountInt
loginSelector = int(input("Select Action:"))
if loginSelector == 1:
#login
print ("action complete")
if loginSelector == 2:
#sign up
accountInt = int(input("Input 4 Digit Pin:"))
while (accountInt >= 9999 or accountInt <= 999):
print("ERROR\nTry Again")
accountInt = int(input("Input 4 Digit Pin:"))
accountInt = str(accountInt)
with open('Account.txt', 'r') as rf:
for line in rf:
if (line == str(accountInt)):
print("error")
with open('Account.txt', 'a') as f:
f.write('\n')
f.write(accountInt)
while True:
loginSetup()
答案 0 :(得分:1)
那是因为,您不是先编写一行文本后接换行符,而是先编写换行符。因此,文件的最后一行没有尾随换行符(并允许比较在那里成功)。
在循环中,line
将是一些在末尾带有换行符的文本(除最后一行以外的所有字符),而str(AccountInt)
将永远不会有换行符。因此无法进行匹配。
在比较之前,您需要从字符串中删除换行符。