HOWTO · Python
How to Delete Line From File in Python
This tutorial discusses how to delete a specific line from a file in Python.
On this page
Python does not provide a built-in operation for removing an arbitrary line from a text file. Read the lines, omit the ones you want to remove, and write the remaining text back. The examples below use temporary files and are self-contained.
Delete Lines by Number in a Python File
Python’s enumerate() gives each line a zero-based index: the first line is index 0. Read the file before opening it for writing, since mode w immediately clears its contents. Use a set when selecting several indexes; every line whose index is in that set is omitted.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("red\ngreen\nblue\nyellow\n")
indexes_to_remove = {1, 3}
lines = path.read_text().splitlines(keepends=True)
path.write_text("".join(
line for index, line in enumerate(lines)
if index not in indexes_to_remove
))
print(path.read_text(), end="")
red
blue
This LF-only example writes retained lines with LF endings. Path.read_text() uses universal newline handling, so CRLF input is converted to \n before writing. If an index is outside the file’s range, it matches no line and has no effect. For large files, a second approach is to process one line at a time into a temporary file, then replace the original after both files are closed.
Method 1
A context manager closes the file even if the block ends early. The read-then-write pattern is straightforward and works for any chosen indexes, but it holds all lines in memory. For large files, use a temporary file in the same directory and replace the original after writing succeeds.
Method 2
For a file small enough to fit in memory, r+ allows reading and writing through one handle. Here, newline="" disables newline translation: readlines() retains each line terminator, including CRLF, and writelines() writes the retained terminators unchanged. After reading, seek to the start and truncate the old contents before writing the retained lines. This avoids opening the original twice, but it is not an atomic update: a failure during the rewrite can leave partial contents. It is not inherently faster than the first pattern.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("red\ngreen\nblue\nyellow\n")
indexes_to_remove = {1, 3}
with path.open("r+", newline="") as file:
lines = file.readlines()
file.seek(0)
file.truncate()
file.writelines(
line for index, line in enumerate(lines)
if index not in indexes_to_remove
)
print(path.read_text(), end="")
red
blue
Delete the First or Last Line from a Python File
List slicing can remove a position while retaining the rest. lines[1:] omits the first line; lines[:-1] omits the last. Check that the list contains lines before writing the sliced result, so the same code also handles a file with no lines.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("first\nmiddle\nlast\n")
lines = path.read_text().splitlines(keepends=True)
without_first = lines[1:]
path.write_text("".join(without_first))
lines = path.read_text().splitlines(keepends=True)
without_last = lines[:-1] if lines else []
path.write_text("".join(without_last))
print(path.read_text(), end="")
middle
The example removes the first line, then removes the last line from what remains. To perform only one operation, keep the corresponding slice and write it once. Slicing an empty list produces an empty list.
Delete a Line That Matches Exact Text
Compare the line’s content without its line-ending characters to the target string. This is an exact, case-sensitive comparison: spaces and other characters remain significant. The loop below removes every matching line. The LF-only fixture retains LF endings; Path.read_text() would normalize CRLF input to \n before writing.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("keep this\nremove this\nremove this\nkeep that\n")
target = "remove this"
lines = path.read_text().splitlines(keepends=True)
retained = [
line for line in lines
if line.rstrip("\r\n") != target
]
path.write_text("".join(retained))
print(path.read_text(), end="")
keep this
keep that
Use line.rstrip("\r\n") rather than strip() when leading or trailing spaces are part of the text to compare. If you intend to remove only the first matching line, locate its index and omit that one position instead.
Delete Lines Containing a Word
To remove lines containing a word or substring, test with in instead of comparing the whole line. This example removes every line containing blue; matching is case-sensitive, and a line containing bluebird also matches. A temporary file lets the original remain intact until the filtered text is ready.
import os
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
temporary_path = Path(directory) / "filtered.txt"
path.write_text("red\nblue bird\ngreen\nbluebird\n")
with path.open("r") as source, temporary_path.open("w") as target:
for line in source:
if "blue" not in line:
target.write(line)
os.replace(temporary_path, path)
print(path.read_text(), end="")
red
green
Create the temporary file in the same directory as the original so replacement stays on the same filesystem. Close both handles before calling os.replace(). Choose a narrower condition, such as checking a whole word with a regular expression, if substring matches are too broad.
Delete the Shortest Line in a Python File
Compare line lengths after removing only the line-ending characters. min() can select an index without guessing a maximum line length. When multiple lines share the minimum length, the first one is selected; removing by index ensures an identical later line is retained. The LF-only fixture writes retained lines with LF endings; Path.read_text() normalizes CRLF input to \n before writing. If there are no lines, there is nothing to remove.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("long line\nx\ncat\ny\n")
lines = path.read_text().splitlines(keepends=True)
if lines:
shortest_index = min(
range(len(lines)),
key=lambda index: len(lines[index].rstrip("\r\n")),
)
del lines[shortest_index]
path.write_text("".join(lines))
print(path.read_text(), end="")
long line
cat
y
Here, x and y are tied for shortest, so only x, which appears first, is removed. If blank lines should not count, filter them out when choosing the index and preserve them in the output.
Delete All Lines from a Python File
Opening an existing file in write mode truncates it as soon as it is opened. Use this only when you intend to discard all contents. A writable handle is required; truncating a file opened in read-only mode is not allowed.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("first\nsecond\n")
with path.open("w"):
pass
print(repr(path.read_text()))
''