Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Replace a Specific Line in a File Using Python

Use pathlib to replace a numbered line in a small text file, or process lines sequentially with fileinput. Learn how to avoid index, overwrite, encoding, and newline mistakes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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")
  1. Set the path, line number, and replacement. The example uses line 3 and a UTF-8 text file named example.txt.
  2. Read and split the file. splitlines(keepends=True) keeps recognized line endings attached to each line.
  3. 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.
  4. 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 describes read_text() as returning the decoded contents as a string and notes that write_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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.