Testing if a String is inside a File. txt

Asked

Viewed 413 times

2

Hello

I’d like to know how I compare a user-typed string with the strings contained in a file. txt

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 for your attention. :)

1 answer

1


The method readline() returns only one line of the file, you could use the readlines() that returns a list of all, where each element is a line, or 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")
  • It worked out, thank you very much !! :)

  • You’re welcome @SZJ08, I’m glad you solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.