To replace specific lines within a text file in Python, consider the use of the fileinput module. This method avoids loading the entire file into memory, making it efficient for large files.
import fileinput with fileinput.input("test.txt", inplace=True) as f: for line in f: if "foo" in line: print(line.replace("foo", "bar"), end='')
With this code, the original file is renamed to a backup, and the standard output is redirected to write into the original file within the loop. Any print statements inside the loop modify the file's contents directly.
For readability, consider these explicit options:
Option 1 (For Small Files):
with open("test.txt", "r") as f: lines = f.readlines() with open("test.txt", "w") as f: for line in lines: if "foo" in line: f.write(line.replace("foo", "bar")) else: f.write(line)
Option 2 (For Large Files):
import tempfile with open("test.txt") as original, tempfile.NamedTemporaryFile(delete=False) as temp: for line in original: if "foo" in line: temp.write(line.replace("foo", "bar").encode()) else: temp.write(line.encode()) temp.flush() os.replace(temp.name, "test.txt")
The above is the detailed content of How Can I Efficiently Replace Lines in a Text File Using Python?. For more information, please follow other related articles on the PHP Chinese website!