Check the line containing a string inside a TXT file

Asked

Viewed 3,080 times

2

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

Example

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

File.txt:

arroz
batata
feijão
carne
laranja

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

3 answers

2

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
...

0

A way to do it in a slightly more extensive 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, looking for the text placed on research, this version is not the fastest but is more didactic.

  • 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.

  • 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 the enumerate; and, finally, there is no need to use a flag achei to check the search result if using the else of for to treat the case of failure.

-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

Mode of use:

$ ./teste.py lara
laranja na linha 4

If you want to exchange the fragment test for an exact test, substitute "in Lines..." for "== Lines...".

Browser other questions tagged

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