我想知道如何將文本文件的多行與單個變量進行比較。我已經部分工作了,但它只與文本文件的最后一行進行比較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()
1 回答

BIG陽
TA貢獻1859條經驗 獲得超6個贊
這是因為您不是先寫一行文本后跟換行符的標準方式,而是先寫換行符。所以文件的最后一行沒有尾隨換行符(并允許比較在那里成功)。
在循環中,line
將是一些在末尾帶有換行符的文本(除了最后一行之外的所有文本),并且str(AccountInt)
永遠不會有換行符。所以不可能匹配。
在比較之前,您需要從字符串中去除換行符。
添加回答
舉報
0/150
提交
取消