Read specific line of a txt file

1

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

I do not want to have to use a loop to go through all those lines, is there any more optimized way to do this?

    
asked by anonymous 16.09.2018 / 20:40

2 answers

5

No, text files are files of sequential bytes, and since each line can have a different number of bytes, there is no direct way to go to a certain line without knowing its position first. To find out 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. This is what the readline() method and its equivalents do.

There are exceptions:

  • If all lines in the file have the same size in bytes, you can multiply by the line number and go straight to the 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, you can scroll back and forth through a smaller path, although this would also run through the file, but in reverse.

  • >
  • The linecache module pointed to in the other response runs through the file once and creates an index, storing the position in bytes within the file where each line is located. This then allows you to position the file on a specific line without going through the other lines, but you must go through the file at least once to create that index before using it.

17.09.2018 / 00:52
1

It is possible, we just use to read the specific position in case line 952 is line 951 because the first line is referenced to position 0:

archive = open('texto.txt', 'r')

print(archive.readlines()[951])

archive.close

Or we can go straight to not consume much memory:

trecho = open('texto.txt', 'r').readlines()[951]

So it will return only one list, not keeping too much memory allocated.

    
21.12.2018 / 12:03