0
0
PythonProgramBeginner · 2 min read

Python Program to Find and Replace Text in File

Use Python's file handling to read the file content with open('filename', 'r'), replace text using str.replace(), then write back with open('filename', 'w') to update the file.
📋

Examples

InputFile content: 'Hello world!' Find: 'world' Replace: 'Python'
OutputFile content after replacement: 'Hello Python!'
InputFile content: 'apple banana apple' Find: 'apple' Replace: 'orange'
OutputFile content after replacement: 'orange banana orange'
InputFile content: 'no match here' Find: 'xyz' Replace: 'abc'
OutputFile content after replacement: 'no match here'
🧠

How to Think About It

To replace text in a file, first read all the text from the file into memory. Then use the replace method on the text to swap the target word with the new word. Finally, write the changed text back to the same file, overwriting the old content.
📐

Algorithm

1
Open the file in read mode and read all its content.
2
Use the string replace method to change the target text to the new text.
3
Open the file again in write mode to overwrite it.
4
Write the modified content back to the file.
5
Close the file.
💻

Code

python
filename = 'sample.txt'
find_text = 'world'
replace_text = 'Python'

with open(filename, 'r') as file:
    content = file.read()

content = content.replace(find_text, replace_text)

with open(filename, 'w') as file:
    file.write(content)

print(f"Replaced '{find_text}' with '{replace_text}' in {filename}.")
Output
Replaced 'world' with 'Python' in sample.txt.
🔍

Dry Run

Let's trace replacing 'world' with 'Python' in a file containing 'Hello world!'.

1

Read file content

content = 'Hello world!'

2

Replace text

content.replace('world', 'Python') results in 'Hello Python!'

3

Write back to file

File now contains 'Hello Python!'

StepContent
1Hello world!
2Hello Python!
3Hello Python!
💡

Why This Works

Step 1: Read the file content

Opening the file in read mode with open(filename, 'r') lets us get all the text to work on.

Step 2: Replace the target text

Using str.replace(find_text, replace_text) swaps all occurrences of the target word with the new word.

Step 3: Write the updated content

Opening the file in write mode with open(filename, 'w') clears old content and saves the new text.

🔄

Alternative Approaches

Using fileinput module
python
import fileinput

filename = 'sample.txt'
find_text = 'world'
replace_text = 'Python'

for line in fileinput.input(filename, inplace=True):
    print(line.replace(find_text, replace_text), end='')
This method edits the file in place line by line, which can be more memory efficient for large files.
Using temporary file
python
import os

filename = 'sample.txt'
tempfile = 'temp.txt'
find_text = 'world'
replace_text = 'Python'

with open(filename, 'r') as file, open(tempfile, 'w') as temp:
    for line in file:
        temp.write(line.replace(find_text, replace_text))

os.replace(tempfile, filename)
This approach writes changes to a temporary file first, then replaces the original file, which is safer for large files or critical data.

Complexity: O(n) time, O(n) space

Time Complexity

Reading and writing the entire file takes time proportional to the file size, so it's O(n). The replace operation also scans the whole text.

Space Complexity

The program stores the whole file content in memory, so space used is proportional to file size, O(n).

Which Approach is Fastest?

Reading and writing the whole file at once is simple but uses more memory. The fileinput method edits line by line, saving memory but may be slower for very large files.

ApproachTimeSpaceBest For
Read all and replaceO(n)O(n)Small to medium files, simple code
fileinput inplaceO(n)O(1)Large files, memory efficient
Temporary fileO(n)O(n)Safe updates, avoids data loss
💡
Always back up your file before replacing text to avoid accidental data loss.
⚠️
Forgetting to write the modified content back to the file, so changes don't save.