Python - Read data to demarcation point

Asked

Viewed 320 times

-1

How to read data from a file (text or binary) up to a marked point for me in it? For example, I wrote a text and put a .(dot) that separates the first part from the second. How do I read only the first part? Only to the point?

  • 1

    You can open the file for reading, read character by character (or a set of them) until you find the demarcated character. If your object is an instance of io.RawIOBase, how is the return of open, you can use the method read.

1 answer

1

Greetings Retronietzsche,

To test this code, first create the "test.txt" file with the following content:

Python é uma linguagem de programação de alto nível, interpretada, de script, 
imperativa, orientada a objetos, funcional, de tipagem dinâmica e forte. #stop
Foi lançada por Guido van Rossum em 1991. 
Wikipédia

Follow the "ler_file" method that receives the parameters "stop" and "file".

The operation is very simple. The method searches in each line of the file "txt" the string of the variable "stop". Remove it along with line breaks and whitespace.

Returns an updated list as a string concatenated to the point delimited in the "stop variable".

arquivo = 'teste.txt'

parar = '#stop'

def ler_arquivo(parar, arquivo):

    lista = []

    arq = open(arquivo, 'r')

    for linha in arq:

        if parar in linha:
            i = linha.index(parar) # indice da marcação para parar
            linha = linha.replace(linha[i:-1],'').strip('\n').strip() # removendo a marcação
            lista.append(linha)
            return ''.join(lista)        
        else:
            lista.append(linha.strip('\n').strip())

    return ''.join(lista)            

    arq.close()


print(ler_arquivo(parar, arquivo))
  • 1

    It’s completely unnecessary to do arq.readlines() in this problem; this will load all the contents of the file in memory and if the file is too big it will be bad for the application and for the server, which can lock the system. Instead, you can iterate straight on arq, which is a generator and will keep only one line of the file in memory at a time.

  • Greetings Anderson, I updated the answer with your tip. Thank you so much for your contribution!

  • 1

    If you are interested, I commented on this in item 6, right at the end of this reply.

Browser other questions tagged

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