Check the line containing a string inside a TXT file

2

I need a help with a program that reads a file and responds in which line it contains a string inside it.

Example

I have a .txt file and inside it I have 5 lines:

File.txt:

arroz
batata
feijão
carne
laranja

I need the program to return me, for example, if I look for orange line 5, if I look for potato, line 2.

    
asked by anonymous 01.04.2018 / 15:15

3 answers

2

You can do the following:

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 verify 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
...
    
01.04.2018 / 15:49
0

One way to do it in a slightly longer version:

#!/usr/bin/env python3

arquivo = 'arquivo.txt'
pesquisa = 'batata'

achei = False

with open(arquivo,'r') as f:
    linha = 1
    for texto in f:
        if pesquisa == texto.strip():
            achei = True
            break
        linha+=1
f.close()

if achei:
    print('Encontrado "{}" na linha {}'.format(pesquisa, linha))
else:
    print('Não encontrei "{}"'.format(pesquisa))

It reads the file line by line, searching for the text placed in search , this version is not the fastest but is more didactic.

    
01.04.2018 / 16:51
-1
#!/usr/bin/env python3

import sys

lines = open("arquivo.txt").readlines()
for i in range(0, len(lines)):
    if sys.argv[1] in lines[i].strip():
        print("%s na linha %d" % (lines[i].strip(), i + 1))
        break

How to use:

$ ./teste.py lara
laranja na linha 4

If you want to change the test of the fragment by an exact test, replace "in lines ..." with "== lines ...".

    
01.04.2018 / 15:51