python - Writing a line between lines -


i writing script have insert line between 2 lines. example:

<tag1>     <subtag1>                 line 1 - text             line 2 - text     </subtag> - #closing of subtag  **--> here have (between closure of subtag , tag1) insert new tag (3 lines, opening tag, body , closing tag)**  </tag1> 

i trying below-mentioned code, not able write in file.

 open ('abc.xml' , "r+") f:      line in f:          if '</subtag>' in line:              f.write('\n text1\n')              f.write('text2')              f.write('text3') 

can please let me know in above code doing wrong, or other idea write code inserting line between 2 lines in file in python?

as per jonrsharpe's comment, easy understand approach read whole file, insert lines need them:

# let's read our input file variable open('input.html', 'r') f:     in_file = f.readlines()  # in_file list of lines  # start building our output out_file = [] line in in_file:     out_file.append(line)  # copy each line, 1 one     if '</subtag>' in line:  # add new entry, after match         out_file.append('    <some new tag>text1</some new tag>\n')  # let's write lines new output file. # re-write on input file now, if wanted! open('out.html', 'w') f:     f.writelines(out_file) 

i started file:

<tag1>     <subtag1>         line 1 - text         line 2 - text     </subtag> </tag1> 

end script produced this:

<tag1>     <subtag1>         line 1 - text         line 2 - text     </subtag>     <some new tag>text1</some new tag> </tag1> 

i hope helps!


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -