How do I search and replace text in a file using Python 3?
Here is my code:
import os
import sys
import fileinput
print (\"Text to search for:\")
te
fileinput already supports inplace editing. It redirects stdout
to the file in this case:
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
(pip install python-util)
from pyutil import filereplace
filereplace("somefile.txt","abcd","ram")
The second parameter (the thing to be replaced, e.g. "abcd" can also be a regex)
Will replace all occurences
def word_replace(filename,old,new):
c=0
with open(filename,'r+',encoding ='utf-8') as f:
a=f.read()
b=a.split()
for i in range(0,len(b)):
if b[i]==old:
c=c+1
old=old.center(len(old)+2)
new=new.center(len(new)+2)
d=a.replace(old,new,c)
f.truncate(0)
f.seek(0)
f.write(d)
print('All words have been replaced!!!')