1

I'm opening file and searching for specific word to replace the last 2 occurrence of that word in a file.

I have opened file and try to replace but it is replacing first 2 occurrence. where as i want to replace last two occurence

s = open("mount.txt").read()
s = s.replace('mickey', 'minnie',2)
f = open("mount.txt", 'w')
f.write(s)
f.close()

This is text is just for example. Actual text is different.

#mount.txt# 

I'm mickey. minnie is my friend.
mickey is the good name given by my parents.
mickey loves to play cricket.
Where as his parents doesn't like Mickey's habit.



#Replaces text[mount.txt]#

I'm mickey. minnie is my friend.
Mickey is the good name given by my parents.
minnie loves to play cricket.
Where as his parents doesn't like minnie's habit.

2 Answers2

2
s = open("mount.txt").read()
sr = s.rsplit('mickey', 2)
s = 'minnie'.join(sr)
f = open("mount.txt", 'w')
f.write(s)
f.close()
Afik Friedberg
  • 332
  • 2
  • 8
0

Here is a possible solution. Note: this version is case sensitive, so mickey and Mickey are NOT treated as the same; but if you need case insensitive replacements this code will at least point you in a possible direction to a complete solution.

def func(word_to_search, replacement_word, num_replacements):
    with open('test.txt') as f:
        old_lines = f.readlines()

    new_lines = []
    counter = 0
    for line in reversed(old_lines):            # iterate in reverse order
        if counter < num_replacements:
            # only check if 'num_replacements' has not been reached yet

            while word_to_search in line:
                line = line.replace(word_to_search, replacement_word, 1)
                counter += 1

                if counter >= num_replacements:
                    # exit while loop because 'num_replacements' has been reached
                    break

        new_lines.append(line)

    # reverse list again to get original order
    new_lines = list(reversed(new_lines))

    with open('test2.txt', 'w') as f:
        f.writelines(new_lines)


if __name__ == '__main__':
    func(
        word_to_search='mickey',
        replacement_word='MINNIE',
        num_replacements=2)

The input:

I'm mickey. minnie is my friend.
mickey is the good name given by my parents.
mickey loves to play cricket.
Where as his parents doesn't like Mickey's habit.

The output (Mickey on the last line was not replaced because it is not all lowercase):

I'm mickey. minnie is my friend.
MINNIE is the good name given by my parents.
MINNIE loves to play cricket.
Where as his parents doesn't like Mickey's habit.
Ralf
  • 16,086
  • 4
  • 44
  • 68