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.
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:
Two choices in that example are important:
- '
splitlines(keepends=True)preserves newline characters so the rewritten file keeps the original line layout.' - '
line_number - 1converts 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:
If you only want to delete the first matching line, stop after the first match instead of removing all of them:
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.
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
- How to delete an item in a list if it exists?
- How to delete items from a dictionary while iterating over it?
- How to delete last item in list?
- How to delete rows from a pandas DataFrame based on a conditional expression
- How to delete the last row of data of a pandas dataframe
- How to determine if a list is subset of another list?
- How to determine if a number is any type of int core or numpy, signed or not?
- How to determine if Python is running inside a virtualenv?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.