Start reading txt from a specific line in Python [duplicate]

1

I have some txt files that follow a pattern:

  

link
  Thieves get caught after sending selfies with stolen iPad to iCloud victim
   There are several types of meliantes Those you have never heard [...]

That is:

  

original link
  title
  content

I would like to know how to do in Python, something style archive.readlines (2 :) (start reading the file from the second line to the end) to get all the content that interests me in these files.

Solution

I was able to accomplish the desired with the code:

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

print(archive.readlines()[1:])

archive.close

Or

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

This will return only one list with the desired one.

    
asked by anonymous 20.12.2018 / 21:07

1 answer

1

Because text files are only sequential byte files, this is not possible. To know where the third line is, you need to read the other two; What .readline() and similar do is read bytes until you find the end-of-line byte to know that the line has ended. As the size of each line is variable, before reading it it is not possible to know where this end of line is:

with open('arquivo.txt') as f:
     f.readline()  # le duas linhas e
     f.readline()  # descarta
     restante = f.readlines()

However, If you know exactly how many bytes have on the first two lines, you can use seek to skip the bytes:

with open('arquivo.txt') as f:
     f.seek(23) # pula 23 bytes
     restante = f.readlines()
    
20.12.2018 / 21:25