将 txt 文件的多行与 python 中的单个变量进行比较

我想知道如何将文本文件的多行与单个变量进行比较。我已经部分工作了,但它只与文本文件的最后一行进行比较


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() 


largeQ
浏览 96回答 1
1回答

BIG阳

这是因为您不是先写一行文本后跟换行符的标准方式,而是先写换行符。所以文件的最后一行没有尾随换行符(并允许比较在那里成功)。在循环中,line将是一些在末尾带有换行符的文本(除了最后一行之外的所有文本),并且str(AccountInt)永远不会有换行符。所以不可能匹配。在比较之前,您需要从字符串中去除换行符。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python