Skip to content
Advertisement

How to search and replace text in a file?

How do I search and replace text in a file using Python 3?

Here is my code:

JavaScript

Input file:

JavaScript

When I search and replace ‘ram’ by ‘abcd’ in above input file, it works as a charm. But when I do it vice-versa i.e. replacing ‘abcd’ by ‘ram’, some junk characters are left at the end.

Replacing ‘abcd’ by ‘ram’

JavaScript

Advertisement

Answer

fileinput already supports inplace editing. It redirects stdout to the file in this case:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement