Python
text file
file handling
line deletion
coding tutorial

How to delete a specific line in a text file using Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Deleting one line from a text file sounds simple, but the details matter if you want to avoid corrupting the file or removing the wrong content. In Python, the usual solution is to read the file, filter out the target line, and write the result back safely.

Delete a Line by Number

If the file is small enough to fit comfortably in memory, the simplest approach is to read all lines, skip one by index, and write the remaining lines back.

This example removes line 3 using one-based numbering:

python
1from pathlib import Path
2
3
4def delete_line(path: str, line_number: int) -> None:
5    file_path = Path(path)
6    lines = file_path.read_text(encoding="utf-8").splitlines(keepends=True)
7
8    if line_number < 1 or line_number > len(lines):
9        raise ValueError(f"line_number must be between 1 and {len(lines)}")
10
11    del lines[line_number - 1]
12    file_path.write_text("".join(lines), encoding="utf-8")
13
14
15delete_line("notes.txt", 3)

Two choices in that example are important:

  • 'splitlines(keepends=True) preserves newline characters so the rewritten file keeps the original line layout.'
  • 'line_number - 1 converts normal human line numbering into Python's zero-based indexing.'

This approach is easy to read and works well for configuration files, logs you are cleaning up, or generated text files with modest size.

Delete Lines by Content

Sometimes you do not know the line number ahead of time. In that case, filtering by content is cleaner than scanning for indexes manually.

The function below removes every line that exactly matches a target string:

python
1from pathlib import Path
2
3
4def delete_matching_lines(path: str, target: str) -> None:
5    file_path = Path(path)
6    lines = file_path.read_text(encoding="utf-8").splitlines(keepends=True)
7    filtered = [line for line in lines if line.rstrip("\n") != target]
8    file_path.write_text("".join(filtered), encoding="utf-8")
9
10
11delete_matching_lines("notes.txt", "DEBUG")

If you only want to delete the first matching line, stop after the first match instead of removing all of them:

python
1from pathlib import Path
2
3
4def delete_first_match(path: str, target: str) -> bool:
5    file_path = Path(path)
6    lines = file_path.read_text(encoding="utf-8").splitlines(keepends=True)
7
8    for index, line in enumerate(lines):
9        if line.rstrip("\n") == target:
10            del lines[index]
11            file_path.write_text("".join(lines), encoding="utf-8")
12            return True
13
14    return False

That is often the safer behavior for data files where duplicate lines may be meaningful.

Use a Temporary File for Large Inputs

For large files, reading everything into memory is unnecessary. A streaming rewrite is safer and scales better: read one line at a time, write every line except the one you want to drop, then replace the original file atomically.

python
1from pathlib import Path
2from tempfile import NamedTemporaryFile
3import os
4
5
6def delete_line_streaming(path: str, line_number: int) -> None:
7    source = Path(path)
8
9    with source.open("r", encoding="utf-8") as infile, \
10         NamedTemporaryFile("w", delete=False, encoding="utf-8") as outfile:
11        for current_number, line in enumerate(infile, start=1):
12            if current_number != line_number:
13                outfile.write(line)
14
15    os.replace(outfile.name, source)
16
17
18delete_line_streaming("big_log.txt", 100_000)

os.replace matters here because it swaps the temporary file into place in a single operation. If your program crashes during processing, the original file is less likely to be left half-written.

Pick the Right Strategy

Use the in-memory version when:

  • the file is small
  • readability matters most
  • you want the shortest possible solution

Use the temporary-file version when:

  • the file may be large
  • you care about safer replacement semantics
  • you are processing logs, exports, or user data

The key idea is the same in both cases: never try to "delete bytes from the middle" of a normal text file in place. Text files are sequences of bytes, so removing one line generally means rewriting the file contents.

Common Pitfalls

  • Off-by-one mistakes. Users think in one-based line numbers, but Python lists use zero-based indexes.
  • Losing newline characters. If you omit keepends=True, your rewritten file can collapse lines together unless you add line breaks back yourself.
  • Opening the file in write mode too early. If you call open(path, "w") before reading, Python truncates the file immediately.
  • Ignoring encoding. Use an explicit encoding such as utf-8, especially when the file may contain non-ASCII text.
  • Deleting by raw string match without trimming line endings. "DEBUG" and "DEBUG\n" are not the same value.

Summary

  • The standard Python solution is read, filter, and rewrite.
  • Deleting by line number is simplest for small files and fixed targets.
  • Deleting by content is better when the exact line position is unknown.
  • For large files, write to a temporary file and replace the original with os.replace.
  • Preserve newline characters and use explicit encodings to avoid subtle file corruption.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.