For a small text file, read its contents into lines, select the target line, replace it, and write the result back. Python counts list positions from zero, so line 3 is at index 2. The example below checks that the requested line exists before changing it and uses an explicit UTF-8 encoding.
Replace a numbered line in a small file
Use pathlib to read and write the file. This version retains each line ending while splitting, and leaves a final line without a line terminator unterminated:
from pathlib import Path
path = Path("example.txt")
line_number = 3 # Human line numbers start at 1
replacement = "This is the replacement text"
text = path.read_text(encoding="utf-8")
lines = text.splitlines(keepends=True)
index = line_number - 1
if not 0 <= index < len(lines):
raise IndexError(f"Line {line_number} does not exist")
ending = "n" if lines[index].endswith("n") else ""
lines[index] = replacement + ending
path.write_text("".join(lines), encoding="utf-8")
- Set the path, line number, and replacement. The example uses line 3 and a UTF-8 text file named
example.txt. - Read and split the file.
splitlines(keepends=True)keeps recognized line endings attached to each line. - Convert to a Python index and check it. Subtract one from the human-counted line number. The bounds check raises an error if that line is absent, instead of silently doing nothing.
- Replace the selected line and write the result.
Path.write_text()writes the complete text and overwrites an existing file of the same name, so the change is not limited to one portion of the file. Python’s pathlib documentation describesread_text()as returning the decoded contents as a string and notes thatwrite_text()overwrites an existing file.
Replace a line by matching its text
If you do not know the target’s line number, choose a selection rule before editing: replace the first matching line, every matching line, or only a match that also satisfies some context. Confirm that a match was found before writing; otherwise, the script could rewrite the file unchanged and give the impression that an edit occurred.
For example, to replace only the first exact match while preserving its line ending:
#1 Best Overall
from pathlib import Path
path = Path("example.txt")
target = "old setting=value"
replacement = "new setting=value"
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
for index, line in enumerate(lines):
content = line.rstrip("rn")
if content == target:
ending = line[len(content):]
lines[index] = replacement + ending
break
else:
raise ValueError(f"Target line not found: {target!r}")
path.write_text("".join(lines), encoding="utf-8")
This example compares the line content without its trailing CR or LF characters, then attaches the original ending to the replacement. It changes only the first exact match. Change the loop deliberately if the intended rule is to replace all matches.
Choose the right approach for file size and recovery
| Approach | Best fit | Memory and recovery |
|---|---|---|
Path.read_text(), transform, then Path.write_text() |
A small file and a clearly selected line | Loads the file contents into memory; writing overwrites the file, so make a copy first if you need an easy rollback. See pathlib’s write_text documentation. |
fileinput with in-place filtering |
Sequential processing, including filtering across files | Processes lines sequentially; its in-place mode moves the original to a backup and directs output to the input file. Choose a backup extension deliberately if you want to retain that copy. See Python’s fileinput documentation. |
For a large file, sequential processing can avoid loading the entire file into memory. An in-place filter is not risk-free: understand its backup behavior and keep a recoverable original when the content matters.
Rank #2
Handle encoding and line endings deliberately
The examples use UTF-8; use the file’s actual encoding if it is different. If you omit the encoding, the default text encoding is locale-specific and can vary between environments. Python’s open documentation explains text encoding and newline handling.
Line endings may be LF (n) or CRLF (rn), among other conventions. Text-mode newline handling can translate line endings, and the numbered-line example’s explicit "n" ending is suitable only when LF is the relevant convention. If byte-for-byte preservation of a file’s newline style matters, use a deliberate strategy—such as opening with newline=""—and verify the behavior on the file format you are editing. Do not assume that retaining line endings with splitlines(keepends=True) alone guarantees preservation through a text-mode write.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




