How to search and replace text in a file
Efficiently replace text in a Python script with:
This snippet opens a file in r+
mode allowing read and write operations safely with automatic file closure. The data
variable holds the content of the file which is then modified using file.replace()
, replacing the target string ('find')
.
Attention, large files
For large files, it might not be wise to read the entire content into memory. Here's an optimized version that reads and replaces line by line to prevent a memory overflow.
Using fileinput
with inplace=True
is like having a road under construction while traffic is still moving.
Interruptions, be gone!
Interruptions during file editing could cause havoc. Come prepped with an error handler to the rescue:
The pathlib way
In newer Python versions (3.5+), you can join the pathlib
club for file manipulations to make it more Pythonic:
Backup, the safety net
Before any in-place file edits, be the smart guy and make a backup. It's like an insurance policy for your data.
Encodings and irregular replacements
Encodings, the untold story
When dealing with files in non-standard encodings or binary data, specify the encoding:
Irregular replacements using regex
For replacing more complex patterns, regular expressions are your friend:
Testing and validation
Follow the mantra of code, test, repeat. Always test your code in a sandbox environment before running it on production. Validate the replacement to ensure it meets your expectations.
Was this article helpful?