Here’s what you can do:
with open('Arquivo.txt') as f:
for l_num, l in enumerate(f, 1): # percorrer linhas e enumera-las a partir de 1
if 'laranja' in l: # ver se palavra esta na linha
print('laranja foi encontrada na linha', l_num)
break
else: # caso não haja break
print('nao foi encontrada a palavra')
Using a function:
def get_line(word):
with open('Arquivo.txt') as f:
for l_num, l in enumerate(f, 1): # percorrer linhas e enumera-las a partir de 1
if word in l: # ver se palavra esta na linha
return l_num
return False # não foi encontrada
print(get_line('laranja')) # 5
print(get_line('feijão')) # 3
print(get_line('banana')) # False
If you want to check that the line is exactly the same as the word you can change the condition to (strip()
):
...
if word == l.strip(): # retirar quebra de linha
...
In fact, the solution works, but it is not the most idiomatic version. If it was deliberate, please ignore the comment, but if you really don’t know, I invite you to read the answer from Miguel which is one more version pythonica.
– Woss
To simplify: when you use the context manager to open the file there is no need to close it manually. The file itself
with
take care of it (see more here); line counting can be simplified by using theenumerate
; and, finally, there is no need to use a flagachei
to check the search result if using theelse
offor
to treat the case of failure.– Woss