Vani
Vani

Reputation: 11

How to replace a text in file?

Basically I am trying to replace A with B, I manage to to change the first line, then the two other lines get deleted and it throws an error:

replace_txt = replace_txt[search_txt]
TypeError: string indices must be integers

My text:

A is best
A is cool
A is awesome

My code:

import fileinput

replace_txt = {'A':'B'}
for line in fileinput.input('text1.txt', inplace=True):
    for search_txt in replace_txt:
        replace_txt = replace_txt[search_txt]
        line = line.replace(search_txt, replace_txt)
    print(line, end='')

Upvotes: 0

Views: 55

Answers (1)

BoarGules
BoarGules

Reputation: 16942

This line

replace_txt = replace_txt[search_txt]

overwrites your lookup dictionary with a string. So the next time round replace_txt is no longer a dictionary so selecting using [ ] gives you an error. Call your lookup dictionary something else.

Upvotes: 1

Related Questions