简体   繁体   中英

Writing a block of text into file

In my task I have to write into a txt file a block of text between two specified words (lines which start withh those words). The input file looks like that:

SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
//
NON_SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
END_NON_LINE
SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
//

And I have to write into file the text between SP_LINE and '//' I've tried with this:

import re

fr=open("various.multi").read()
gr=open("locus.txt",'w')

for m in re.finditer("SP_LINE",fr):
    a=int(m.start())
    for n in re.finditer("//", fr[a:]):
        b=int(n.end())
        gr.write(fr[a:b])
gr.close()

But it doesn't work

Well, you can be clever here. What you're essentially saying is that you need to remove the strings 'SP_LINE' and '//' from the file. So, simplify your code like so:

import re

gr=open("locus.txt",'w')

for line in open('data.txt'):
    if re.match('SP_LINE|//', line):
        continue
    gr.write(line)
gr.close()

Try this:

import re

fr=open("various.multi").read()
gr=open("locus.txt",'w')

for m in re.finditer(r"\bSP_LINE\b",fr):
    for n in re.finditer(r"//", fr[m.end():]):
        gr.write(fr[m.start():m.end()+n.end()])
        break
gr.close()

Does this work?

import re

fr=open("various.multi").read()
gr=open("locus.txt",'w')

for m in re.finditer("SP_LINE",fr):
    a = int(m.start())
    b = a + int(re.search("//", fr[a:]).start())
    gr.write(fr[a:b])
gr.close()

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