Read specific line of a txt file

Asked

Viewed 3,835 times

1

I have a file of 1000 lines and I want to read line 952.

I don’t want to have to use a loop to go through all these lines, there’s some more optimized way to do this?

1 answer

5


No, text files are sequential byte files, and since each line can have a different number of bytes, there is no direct way to get to a certain line without knowing its position first. To know where the next line is you need to read the bytes of the file until you find the byte that indicates the end of the line. That’s what the method readline() and their equivalents make.

There are exceptions:

  • If all the file lines is the same size in bytes, you can multiply by the line number and go straight to position:

    tamanho_da_linha = 60 # todas as linhas do arquivo tem 60 bytes
    with open(nome_arq) as f:
        f.seek(tamanho_da_linha * 952) 
        # vai direto para a posicão da linha 952
        linha = f.readline()
    
  • If you already know that the file has 1000 lines, it is possible to go backwards and go down a smaller path, although this would also go through the file, but in reverse.

  • The module linecache pointed in the other answer goes through the file only once and creates a remissive index, storing the position in bytes within the file where each line is. This allows you to then position the file on a specific line without going through the other lines, but you need to scroll through the file at least once to create that index before using.

  • Nosklo, thank you so much for your reply, she gave me good ideas to solve the problem.

Browser other questions tagged

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