Testing if a String is inside a .txt File

2

Hello

I would like to know how I compare a string entered by the user with the strings contained in a .txt file

My last attempt was like this, but I did not get the result I wanted:

f = open("Testando.txt","r")
r = f.readline()
nome = input ("Digite qualquer coisa : ")
for line in r :
    if line == nome :
        print("já existe um nome igual")
    else :
        print("Obrigado pela nova interação")
input("Pressione em qualquer tecla para sair do programa")
f.close()*

Thank you in advance for your attention. :)

    
asked by anonymous 09.04.2017 / 23:48

1 answer

1

The method readline() returns only one line of the file , you could use readlines() which returns you a list with all, where each element is a line, or with the way below (using a generator):

nome = input ("Digite qualquer coisa : ")
with open('Testando.txt',  'r') as f:
    for line in f: # percorrer gerador
        if nome.lower() == line.lower().strip(): # retirar qubras de linha e comparar com ambas sendo minusculas
            print('já existe um nome igual')
            break
    else: # isto acontece se tivermos saido do for sem que tenha havido break 
        print("Obrigado pela nova interação")
input("Pressione em qualquer tecla para sair do programa")
    
10.04.2017 / 00:11