python - Replace all lines [fromString ,toString] in file -
i replace section of text in text file given string. example, given following file content:
1 ---from here--- 2 ---to here--- 3
i write python function upon initiation in format of fashion :
replacesection('pathtofile','---from here---\n','---to here---\n','woo hoo!\n')
this should change original file to:
1 woo hoo! 3
i have come straightforward implementation (below) believe has disadvantages, , i'm wondering if there simpler implementation :
- the code long, makes understanding little cumbersome
- i iterate on code twice (instead of inplace replacements) - seems inefficient
this same implementation use c++ code, , guess python has hidden beauties make implementation more elegant
def replacesection(pathtofile,sectionopener,sectioncloser,replacewith = ''): ''' delete lines in section of given file , put instead customized text. return: none if replacement performed , -1 otherwise. ''' f = open(pathtofile,"r") lines = f.readlines() f.close() if sectionopener in lines: iswrite = true # while outside block , current line should kept f = open(pathtofile,"w") #write each line until reaching section opener # write nothing until reaching section end. line in lines : if line == sectionopener: iswrite = false if iswrite: # outside undesired section , hence want keep current line f.write(line) else: if line == sectioncloser: # it's last line of section f.write(replacewith) ) iswrite = true else: # current line block wish delete # don't write it. pass f.flush() f.close() else: return -1
here's itertools
based approach:
from itertools import takewhile, dropwhile, chain, islice open('input') fin, open('output', 'w') fout: fout.writelines(chain( takewhile(lambda l: l != '---from here---\n', fin), ['woo hoo!\n'], islice(dropwhile(lambda l: l != '---to here---\n', fin), 1, none) ) )
so, until marker, write out original lines, line(s) want, then, ignore until end marker, , write remaining lines (skipping first it'll end marker)...
Comments
Post a Comment