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:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )

input( '\n\n Press Enter to exit...' )

Input file:

hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd

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'

hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd

Solution 1

As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.

# Read in the file
with open('file.txt', 'r') as file :
  filedata =

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:

Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.

Solution 2

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='')

Solution 3

As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:

 # Read in the file
filedata = None
with file = open('file.txt', 'r') :
  filedata =

# Replace the target string
filedata.replace('ram', 'abcd')

# Write the file out again
with file = open('file.txt', 'w') :

But this code WILL work (I've tested it):

f = open(filein,'r')
filedata =

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')

Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.

Solution 4

You can do the replacement like this

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))

Solution 5

You can also use pathlib.

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)

Solution 6

(pip install python-util)

from pyutil import filereplace


Will replace all occurences of "abcd" with "ram".
The function also supports regex by specifying regex=True

from pyutil import filereplace


Disclaimer: I'm the author (

Solution 7

This answer works for me. Open the file in read mode. Read the file in string format. Replace the text as intended. Close the file. Again open the file in write mode. Finally, write the replaced text to the same file.

    with open("file_name", "r+") as text_file:
        texts =
        texts = texts.replace("to_replace", "replace_string")
    with open(file_name, "w") as text_file:
except FileNotFoundError as f:
    print("Could not find the file you are trying to read.")

Solution 8

Late answer, but this is what I use to find and replace inside a text file:

with open("test.txt") as r:
  text ="THIS", "THAT")
with open("test.txt", "w") as w:


Solution 9

With a single with block, you can search and replace your text:

with open('file.txt','r+') as f:
    filedata =
    filedata = filedata.replace('abc','xyz')

Solution 10

Your problem stems from reading from and writing to the same file. Rather than opening fileToSearch for writing, open an actual temporary file and then after you're done and have closed tempFile, use os.rename to move the new file over fileToSearch.

Solution 11

My variant, one word at a time on the entire file.

I read it into memory.

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)


Solution 12

I have done this:

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()

Solution 13

def word_replace(filename,old,new):
    with open(filename,'r+',encoding ='utf-8') as f:
        for i in range(0,len(b)):
            if b[i]==old:
    print('All words have been replaced!!!')

Solution 14

I tried this and used readlines instead of read

with open('dummy.txt','r') as file:
    list = file.readlines()
print(f'before removal {list}')
for i in list[:]:

print(f'After removal {list}')
with open('dummy.txt','w+') as f:
    for i in list:

Solution 15

I modified Jayram Singh's post slightly in order to replace every instance of a '!' character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I'm very new at coding so apologies if my post is inappropriate in any way, but this worked for me.

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1

Solution 16

Besides the answers already mentioned, here is an explanation of why you have some random characters at the end:
You are opening the file in r+ mode, not w mode. The key difference is that w mode clears the contents of the file as soon as you open it, whereas r+ doesn't.
This means that if your file content is "123456789" and you write "www" to it, you get "www456789". It overwrites the characters with the new input, but leaves any remaining input untouched.
You can clear a section of the file contents by using truncate(<startPosition>), but you are probably best off saving the updated file content to a string first, then doing truncate(0) and writing it all at once.
Or you can use my library :D

Solution 17

I got the same issue. The problem is that when you load a .txt in a variable you use it like an array of string while it's an array of character.

swapString = []
with open(filepath) as f: 
    s =
for each in s:
s = swapString

Solution 18

you can use sed or awk or grep in python (with some restrictions). Here is a very simple example. It changes banana to bananatoothpaste in the file. You can edit and use it. ( I tested it worked...note: if you are testing under windows you should install "sed" command and set the path first)

import os 
newtext=" BananaToothpaste"
os.system('sed -i "s/{}/{}/g" {}'.format(oldtext,newtext,file))
#print(f'sed -i "s/{oldtext}/{newtext}/g" {file}')
print('This command was applied:  sed -i "s/{}/{}/g" {}'.format(oldtext,newtext,file))

if you want to see results on the file directly apply: "type" for windows/ "cat" for linux:

os.popen("type " + file).read()
os.popen("cat " + file).read()

Solution 19

I have worked this out as an exercise of a course: open file, find and replace string and write to a new file.

class Letter:

    def __init__(self):

        with open("./Input/Names/invited_names.txt", "r") as file:
            # read the list of names
            list_names = [line.rstrip() for line in file]
            with open("./Input/Letters/starting_letter.docx", "r") as f:
                # read letter
                file_source =
            for name in list_names:
                with open(f"./Output/ReadyToSend/LetterTo{name}.docx", "w") as f:
                    # replace [name] with name of the list in the file
                    replace_string = file_source.replace('[name]', name)
                    # write to a new file

brief = Letter()

Solution 20

def findReplace(find, replace):

    import os 

    src = os.path.join(os.getcwd(), os.pardir) 

    for path, dirs, files in os.walk(os.path.abspath(src)):

        for name in files: 

            if name.endswith('.py'): 

                filepath = os.path.join(path, name)

                with open(filepath) as f: 

                    s =

                s = s.replace(find, replace) 

                with open(filepath, "w") as f:


Solution 21

Like so:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text =
    f.write(text.replace(word, replacement))