简体   繁体   中英

Write lines up to matched string in python

I've the input file as :

Input file:

HEAD    xxxxxxx xxxx
;;;;;;;;;;;;;;;;              
..................
;;;;;;;;;;;;;
..............                                                                    

MODEL        1 

ENDMDL      
;;;;;;;;;;;;;;;;              
..................
;;;;;;;;;;;;;

MODEL        2

ENDMDL  

;;;;;;;;;;;;;;;;              
..................
;;;;;;;;;;;;;
..............

MODEL        3

ENDMDL 

Would like to match string “MODEL 2” and print only above lines Desired output:

HEAD    xxxxxxx xxxx
;;;;;;;;;;;;;;;;              
..................
;;;;;;;;;;;;;
..............                                                                    

MODEL        1 

ENDMDL 

Also I would prefer to read a file and write it in same file.

I found myself this one does what i want.

def transp(inputt):
    with open(inputt,'r+') as f:
        f.write(f.read().split("ENDMDL")[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM