Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Read file from and to specific lines of text

I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length.
Say i have this text file:

Something here...  
... ... ...   
Start                      #I want this block of text 
a b c d e f g  
h i j k l m n  
End                        #until this line of the file
something here...  
... ... ...  

I hope you know what i mean. i was thinking of iterating through the file then search using regular expression to find the line number of "Start" and "End" then use linecache to read from Start line to End line. But how to get the line number? what function can i use?

like image 445
BPm Avatar asked Sep 26 '11 18:09

BPm


People also ask

How do you read multiple lines in a text file in Python?

To read multiple lines, call readline() multiple times. The built-in readline() method return one line at a time. To read multiple lines, call readline() multiple times.


1 Answers

If you simply want the block of text between Start and End, you can do something simple like:

with open('test.txt') as input_data:
    # Skips text before the beginning of the interesting block:
    for line in input_data:
        if line.strip() == 'Start':  # Or whatever test is needed
            break
    # Reads text until the end of the block:
    for line in input_data:  # This keeps reading the file
        if line.strip() == 'End':
            break
        print line  # Line is extracted (or block_of_lines.append(line), etc.)

In fact, you do not need to manipulate line numbers in order to read the data between the Start and End markers.

The logic ("read until…") is repeated in both blocks, but it is quite clear and efficient (other methods typically involve checking some state [before block/within block/end of block reached], which incurs a time penalty).

like image 145
Eric O Lebigot Avatar answered Oct 13 '22 00:10

Eric O Lebigot