Search and Replace Lines in Files with Python
Suppose we have a text file and want to modify specific lines by replacing a certain word with another. We initially consider loading the entire file into memory for processing and writing it back. However, a more efficient approach exists.
Using the fileinput Module
The fileinput module offers a straightforward solution. By utilizing its input() function, we can iterate over the file line by line while modifying it in-place. Here's an example:
This code replaces occurrences of 'foo' with 'bar' in the file, line by line. As fileinput writes directly to the original file, no intermediate file is created.
Alternative Approaches
For small files, an alternative approach involves:
For larger files, consider:
This approach requires additional temporary storage space but is efficient for large files.
Conclusion
Depending on the file size and specific requirements, these approaches provide efficient methods for searching and replacing lines in a file using Python.
The above is the detailed content of How Can I Efficiently Search and Replace Text Within Files Using Python?. For more information, please follow other related articles on the PHP Chinese website!