Reputation: 2059
I would like to replace a certain section of text in my text file with a given string. For example, given the following file content:
1
---From here---
2
---To here---
3
I would like to write a python function that upon initiation in a format of this fashion :
replaceSection('pathToFile','---From here---\n','---To here---\n','Woo Hoo!\n')
This should change the original file to:
1
Woo Hoo!
3
I have come up with a straightforward implementation (below) but I believe it has some disadvantages, and I'm wondering if there is a simpler implementation :
This is the same implementation I would use with my C++ code, and I guess Python has some hidden beauties that would make the implementation more elegant
def replaceSection(pathToFile,sectionOpener,sectionCloser,replaceWith = ''):
'''
Delete all the lines in a certain section of the given file and put instead a customized text.
Return:
None if a replacement was performed and -1 otherwise.
'''
f = open(pathToFile,"r")
lines = f.readlines()
f.close()
if sectionOpener in lines:
isWrite = True # while we are outside the block and current line should be kept
f = open(pathToFile,"w")
#Write each line until reaching a section opener
# from which write nothing until reaching the section end.
for line in lines :
if line == sectionOpener:
isWrite = False
if isWrite:
# We are outside the undesired section and hence want to keep current line
f.write(line)
else:
if line == sectionCloser:
# It's the last line of the section
f.write(replaceWith)
)
isWrite = True
else:
# Current line is from the block we wish to delete
# so don't write it.
pass
f.flush()
f.close()
else:
return -1
Upvotes: 0
Views: 176
Reputation: 142156
Here's an itertools
based approach:
from itertools import takewhile, dropwhile, chain, islice
with open('input') as fin, open('output', 'w') as 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 we get to the from marker, write out the original lines, then the line(s) you want, then, ignore everything until the end marker, and write the remaining lines (skipping the first as it'll be the end marker)...
Upvotes: 1
Reputation: 14209
Here you can just find where your 2 patterns are: this delimits a portion of text, and you just have to replace it by your new pattern:
>>> f = my_file.readlines()
>>> beg = f.index('---From here---')
>>> end = f.index('---To here---') + len('---To here---')
>>> print f.replace(f[beg:end], 'Woo woo !')
1
Woo woo !
3
Beware of the length of your 2nd delimiter (hence the f.index('---To here---') + len('---To here---')
).
Upvotes: 1