How to find and replace within a text file using Python?

Finding and replacing text within files is a common task in Python. You can read a file, replace specific text, and write the result to a new file using built-in file operations and string methods.

Basic Find and Replace

The following example reads from 'foo.txt', replaces all occurrences of 'Poetry' with 'Prose', and writes the result to 'bar.txt' −

# Create sample input file first
with open('foo.txt', 'w') as f:
    f.write("Poetry is often considered the oldest form of literature.\n")
    f.write("Poetry today is usually written down, but is still sometimes performed.\n")

# Read, replace, and write to new file
f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')

for line in f1:
    print(line.strip())
    f2.write(line.replace('Poetry', 'Prose'))

f1.close()
f2.close()

# Read and display the modified file
f2 = open('bar.txt', 'r')
print("\nAfter replacement:")
for line in f2:
    print(line.strip())
f2.close()
Poetry is often considered the oldest form of literature.
Poetry today is usually written down, but is still sometimes performed.

After replacement:
Prose is often considered the oldest form of literature.
Prose today is usually written down, but is still sometimes performed.

Using Context Managers (Recommended)

A better approach uses context managers to automatically handle file closing −

# Create sample file
with open('foo.txt', 'w') as f:
    f.write("Poetry is beautiful art.\nPoetry expresses emotions.\n")

# Find and replace using context managers
with open('foo.txt', 'r') as input_file:
    with open('bar.txt', 'w') as output_file:
        for line in input_file:
            modified_line = line.replace('Poetry', 'Prose')
            output_file.write(modified_line)

# Display results
with open('bar.txt', 'r') as f:
    content = f.read()
    print(content)
Prose is beautiful art.
Prose expresses emotions.

In-Place Replacement

To modify the original file instead of creating a new one −

# Create sample file
with open('sample.txt', 'w') as f:
    f.write("Python is great.\nPython is powerful.\n")

# Read entire file, replace, and write back
with open('sample.txt', 'r') as f:
    content = f.read()

modified_content = content.replace('Python', 'JavaScript')

with open('sample.txt', 'w') as f:
    f.write(modified_content)

# Display modified file
with open('sample.txt', 'r') as f:
    print(f.read())
JavaScript is great.
JavaScript is powerful.

Multiple Replacements

You can chain multiple replacements or use a dictionary approach −

# Create sample file
with open('text.txt', 'w') as f:
    f.write("I love cats and dogs. Cats are cute.\n")

# Define replacements
replacements = {'cats': 'birds', 'dogs': 'fish', 'Cats': 'Birds'}

with open('text.txt', 'r') as f:
    content = f.read()

# Apply all replacements
for old, new in replacements.items():
    content = content.replace(old, new)

print(content)
I love birds and fish. Birds are cute.

Conclusion

Use context managers (with statements) for automatic file handling. For simple replacements, use str.replace(). For complex patterns, consider using the re module with regular expressions.

Updated on: 2026-03-24T19:35:51+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements