In this article, we will see how to delete a line from a file using Python.

There are various ways to delete a specific line in a file using Python. Here are some of the ways to do that:

1. Using the fileinput module:

This module offers a simple way to delete a particular line as well as the ability to alter a file in real time. Following is the example code to delete a line of string from the file:

import fileinput

file_to_modify = "file.txt"
line_to_delete = "delete this line"

for line in fileinput.input(file_to_modify, inplace=True):
    if line_to_delete in line:
        continue
    print(line, end='')

2. Using List:

After reading the contents of the file into a list, you should then write the list back into the file:

You will be able to manage the contents of the file as a list using this method, which will make it much simpler for you to delete individual lines. The line that begins at the index that you provide can be removed using the following code example:

file_to_modify = "file.txt"
line_index = 3

with open(file_to_modify, 'r') as f:
    lines = f.readlines()

del lines[line_index]

with open(file_to_modify, 'w') as f:
    f.writelines(lines)

3. Using sed

If you would rather work with tools accessible via the command line, the sed command can be used to delete a particular line from within a file.

Here is the example program:

import subprocess

file_to_modify = "file.txt"
line_number = 3

subprocess.run(["sed", "-i", f"{line_number}d", file_to_modify])

In the above program, modify the line_number and file_name as per your requirement.

Categorized in:

Tagged in: