Create a file-based literal text search-and-replace utility.
How It Works
Read a UTF-8 text file, replace an exact target substring, and write the updated contents to a separate output file. Check target presence and keep an untouched original to avoid irreversible accidental changes.
Step-by-Step Example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory_name:
source_path = Path(directory_name) / 'notes.txt'
output_path = Path(directory_name) / 'updated.txt'
source_path.write_text('Status: draft', encoding='utf-8')
output_path.write_text(source_path.read_text(encoding='utf-8').replace('draft', 'review'), encoding='utf-8')
print(output_path.read_text(encoding='utf-8'))
Understanding the Example
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
- The expression "Path(directory_name) / 'notes.txt'" supplies the value stored as 'source_path'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
Status: review
Where This Fits in a Real Program
Before putting the technique into a larger program, identify the required inputs and which results are returned. Choose what should happen with invalid or missing data, and test a small valid case and a failing case independently.
Practice: Try It Yourself
For very large files, consider a streaming approach instead of reading everything into memory.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Overwriting the original file without a backup or accidentally using regex syntax in a literal replacement.
- Add an option to report the number of replacements before writing.
Key Takeaways
- Create a file-based literal text search-and-replace utility.
- Read a UTF-8 text file, replace an exact target substring, and write the updated contents to a separate output file.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.