How to Replace a Specific Line in a File Using Python

To replace a specific line in a file using Python, read every line into a list with readlines(), assign new text to that line’s index, then write the list back with writelines(). Python can’t overwrite one line in place, so the file is always rewritten:

with open("stores.txt") as f:
    lines = f.readlines()
lines[2] = "Status: closed\n"   # line 3
with open("stores.txt", "w") as f:
    f.writelines(lines)

Every output below comes from a real run on Python 3.12.5 under Windows 11, using a small store record from Austin, Texas.

I’ll also cover matching a line by its text, huge files that shouldn’t sit in memory, the fileinput module, regex edits, and the newline mistakes that quietly break files.

Replace a specific line by number with readlines()

Here’s the sample file, stores.txt, with five lines. Line 3 holds the status, and since lists start at zero, that’s lines[2]:

Store: Austin, TX
Manager: Emily Carter
Status: open
Last audit: 2026-03-14
Monthly rent: $4,250.00
with open("stores.txt", encoding="utf-8") as f:
    lines = f.readlines()

print("Line 3 before:", repr(lines[2]))
lines[2] = "Status: closed\n"          # index 2 is line 3

with open("stores.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

with open("stores.txt", encoding="utf-8") as f:
    print(f.read())

Output:

Line 3 before: 'Status: open\n'
Store: Austin, TX
Manager: Emily Carter
Status: closed
Last audit: 2026-03-14
Monthly rent: $4,250.00
Command Prompt output of Python replacing line 3 of a text file with readlines and writelines
The old third line is printed first, then the whole file with the status changed to closed.

Notice the new text ends with \n. Each item from readlines() keeps its newline, so yours needs one too. If reading files is new to you, start with reading a file line by line in Python.

Replace a line that matches text in a file

Line numbers shift when someone edits the file by hand. Matching on a prefix is sturdier. This version uses pathlib and stops at the first hit:

from pathlib import Path

path = Path("stores.txt")
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)

for i, line in enumerate(lines):
    if line.startswith("Manager:"):
        print(f"Found on line {i + 1}: {line.strip()}")
        lines[i] = "Manager: James Walker\n"
        break                          # first match only
else:
    print("No Manager line found")

path.write_text("".join(lines), encoding="utf-8")
print(path.read_text(encoding="utf-8"))

Output:

Found on line 2: Manager: Emily Carter
Store: Austin, TX
Manager: James Walker
Status: open
Last audit: 2026-03-14
Monthly rent: $4,250.00
Command Prompt output of Python finding the Manager line in a text file and replacing it
The script reports where it found the Manager line, then shows the file with the new manager’s name.

Drop the break to replace every matching line. The for/else pattern prints a warning when nothing matches. For changing words inside a line instead, see replacing multiple characters in a string.

How do you replace a line in a large file without loading it all?

A 2 GB log won’t fit comfortably in a list. Stream it instead: copy each line to a temporary file, swap in the changed one, then replace the original with os.replace():

import os
import tempfile

src = "orders.csv"
with open(src, "w", encoding="utf-8") as f:            # sample: 100,000 order rows
    f.write("order_id,state,total_usd\n")
    for n in range(1, 100_001):
        f.write(f"{n},TX,{n % 500 + 0.99:.2f}\n")

target = 50_000                                         # line number to change
fd, tmp = tempfile.mkstemp(dir=".", suffix=".tmp")
with open(src, encoding="utf-8") as fin, os.fdopen(fd, "w", encoding="utf-8") as fout:
    for number, line in enumerate(fin, start=1):
        if number == target:
            print("Old:", line.strip())
            line = "49999,CA,499.99\n"
        fout.write(line)
os.replace(tmp, src)                                    # swap in the new file

with open(src, encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        if number == target:
            print("New:", line.strip())
            break

Output:

Old: 49999,TX,499.99
New: 49999,CA,499.99
Command Prompt output of Python replacing line 50,000 of a 100,000-row CSV file through a temporary file
Line 50,000 switches from TX to CA, and the rest of the 100,000 rows are copied unchanged.

Memory use stays flat whatever the file size. Creating the temp file in the same folder matters, because os.replace() is only atomic on one drive. If you want a backup first, copying a file with shutil takes one line.

Edit a file in place with the fileinput module

fileinput with inplace=True does the temp-file work for you. While the loop runs, print() writes into the file, and backup keeps the old copy:

import fileinput

with fileinput.input("stores.txt", inplace=True, backup=".bak", encoding="utf-8") as f:
    for line in f:
        if f.filelineno() == 5:
            line = "Monthly rent: $4,400.00\n"
        print(line, end="")            # print() writes into the file here

with open("stores.txt", encoding="utf-8") as f:
    print(f.read())
with open("stores.txt.bak", encoding="utf-8") as f:
    print("Backup still has:", f.readlines()[4].strip())

Output:

Store: Austin, TX
Manager: Emily Carter
Status: open
Last audit: 2026-03-14
Monthly rent: $4,400.00

Backup still has: Monthly rent: $4,250.00
Command Prompt output of Python fileinput editing line 5 in place and keeping a .bak backup
The rent line now reads $4,400.00, while the .bak backup still holds the old $4,250.00 value.

Forget end="" and you’ll get blank lines between every row, because each line already has a newline. I skip fileinput in code that logs to the console, since stray prints land in the file, and write the list to a file myself instead.

Update part of a line with re.subn()

Sometimes you only need to change a value inside a line. re.subn() with re.MULTILINE edits matching lines across the whole text and tells you how many changed:

import re
from pathlib import Path

path = Path("stores.txt")
text = path.read_text(encoding="utf-8")

new_text, count = re.subn(r"^(Last audit: )\d{4}-\d{2}-\d{2}$",
                          r"\g<1>2026-10-10", text, flags=re.MULTILINE)
path.write_text(new_text, encoding="utf-8")
print(f"Replaced {count} line(s)")
print(new_text)

Output:

Replaced 1 line(s)
Store: Austin, TX
Manager: Emily Carter
Status: open
Last audit: 2026-10-10
Monthly rent: $4,250.00

A count of zero means the pattern missed, which is a good thing to check before saving. Writing the result back works like any string written to a file in Python.

Avoid newline and line-number mistakes when replacing lines

Two bugs cause most broken files. A replacement without \n glues two lines together, and a line number past the end raises IndexError:

lines = ["Store: Austin, TX\n", "Status: open\n", "Manager: Emily Carter\n"]

bad = lines.copy()
bad[1] = "Status: closed"              # forgot the newline
good = lines.copy()
good[1] = "Status: closed\n"
print("Missing newline:", repr("".join(bad)))
print("With newline:   ", repr("".join(good)))

line_number = 7
if not 1 <= line_number <= len(lines):
    print(f"Line {line_number} doesn't exist; the file has {len(lines)} lines")

Output:

Missing newline: 'Store: Austin, TX\nStatus: closedManager: Emily Carter\n'
With newline:    'Store: Austin, TX\nStatus: closed\nManager: Emily Carter\n'
Line 7 doesn't exist; the file has 3 lines

Remember that people count lines from 1 and lists count from 0. If stray newlines are already in your data, removing newlines from a string cleans them up.

Line replacement methods compared

MethodMemoryBest for
readlines() + indexWhole fileSmall files, known line number
Loop + startswith()Whole fileLines found by their text
Temp file + os.replace()One lineLarge files, safe writes
fileinput inplaceOne lineQuick scripts with a backup
re.subn()Whole fileChanging a value inside lines

If you’re working with files a lot, these pick up where this one stops:

Frequently asked questions

How do I replace a specific line in a file in Python?

Read the lines with readlines(), set lines[n - 1] to the new text ending in \n, and write them back with writelines().

Can Python change one line without rewriting the file?

Not for text of a different length. Files store bytes in sequence, so the rest of the file has to be rewritten.

How do I replace a line in a very large file?

Stream it line by line into a temporary file in the same folder, then call os.replace() to swap it in.

Why do I get blank lines after using fileinput?

Each line already ends with a newline. Use print(line, end="") so print() doesn’t add another.

How do I replace every line that contains a word?

Loop over the lines with enumerate(), test if word in line, and assign the new text without breaking out of the loop.

Where is the fileinput module documented?

See fileinput in the Python docs, including the inplace and backup options.