Python Program to Find and Replace Text in File
open('filename', 'r'), replace text using str.replace(), then write back with open('filename', 'w') to update the file.Examples
How to Think About It
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
Code
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}.")
Dry Run
Let's trace replacing 'world' with 'Python' in a file containing 'Hello world!'.
Read file content
content = 'Hello world!'
Replace text
content.replace('world', 'Python') results in 'Hello Python!'
Write back to file
File now contains 'Hello Python!'
| Step | Content |
|---|---|
| 1 | Hello world! |
| 2 | Hello Python! |
| 3 | Hello 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
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='')
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)
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Read all and replace | O(n) | O(n) | Small to medium files, simple code |
| fileinput inplace | O(n) | O(1) | Large files, memory efficient |
| Temporary file | O(n) | O(n) | Safe updates, avoids data loss |