简体   繁体   English

在python中将行写入匹配的字符串

[英]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:想要匹配字符串“MODEL 2”并仅在行上方打印所需的输出:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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