Ohad Dan
Ohad Dan

Reputation: 2059

Replace all lines [fromString ,toString] in file

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 :

Upvotes: 0

Views: 176

Answers (2)

Jon Clements
Jon Clements

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

Emmanuel
Emmanuel

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

Related Questions