Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将txt文件的多行与单个变量进行比较_Python - Fatal编程技术网

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

在python中将txt文件的多行与单个变量进行比较,python,Python,我想知道如何将文本文件的多行与单个变量进行比较。我已经让它部分工作,但它只比较了文本文件的最后一行 def loginSetup(): global loginSelector global accountInt loginSelector = int(input("Select Action:")) if loginSelector == 1: #login print ("acti

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

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

这是因为,你不是先写一行文字,然后写一行新行,而是先写一行新行。因此,文件的最后一行没有尾随的换行符,并允许在此进行比较

在循环中,除了最后一行之外,行将是一些在末尾有换行符的文本,Straccount将永远不会有换行符。所以不可能匹配


在比较之前,您需要先从字符串中删除换行符。

谢谢,这很有帮助。您有没有办法让我看看代码中的换行符是什么样子的呢?再次感谢。除了在文本之后编写换行符外,一个简单的更改是将换行符与line.rstrip进行比较,而不是与for循环中的行进行比较。