Hello, is it possible to switch to a given string in a file in python, that is, I don’t need to read it completely, for example, read from the third to fifth line, while I don’t know how many bytes each of them contains?

2 answers 2

Since the score starts from zero, the third line will have an index of 2, the fifth will have 4

filename - file name

text = open(filename, 'r').readlines()[2:4]

we receive the list from the necessary lines text = '\n'.join(text)

we connect lines in one, but with hyphenation

    I advise you to use ConfigParser, it is most suitable for your idea. Here is a wiki for examples https://wiki.python.org/moin/ConfigParserExamples

    • Could you give me an example - how can you read from the third to the fifth line of an arbitrary text file (in which there are no sections - [section] ) with the help of ConfigParser? - MaxU
    • I do have such sections in the file, but in general, this method does not seem to work. - Lamer
    • @MaxU if there are no sections, read nothing - Insider