Reading in a text file in a given range of lines

Is it possible to read a range of lines of lines from a text file, for example, from line 20 to 52?

I open the file and read the file as follows:

text_file = open(file_to_save, "r")
line = text_file.readline()

but just want to save the data in a given range or, if possible, read from a line after a line containing --- data --- to another line containing - end of data -

I looked through the documentation and online examples and can only find examples that indicate a new line or something.

+6
source share
3 answers

You can use for a file object and use iteration to read only certain lines: itertools.islice()

import itertools

with open(file_to_save, "r") as text_file:
    for line in itertools.islice(text_file, 19, 52):
         # do something with line

20 52; Python 0, 1 0.

; , next() , , "" .

, readline(); .

+24

. enumerate() if:

text_file = open(file_to_save, "r")
lines = []
for index, text in enumerate(text_file):
    if 19 <= index <= 51:
        lines.append(text)

readlines() slice:

text_file = open(file_to_save, "r")
lines = text_file.readlines()
lines = lines[19:52]
+5

HM, you can try something with while while .... but you need to know to which line you want to load the text, which is not the best way:

text_file=open(name,'r')
line=text.readline()
while line!=(" ") #type the line where you want it to stop
print (line
-1
source

Source: https://habr.com/ru/post/1548196/


All Articles