Open In App

Python Program to Delete Specific Line from File

Last Updated : 26 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to delete the specific lines from a file using Python

Throughout this program, as an example, we will use a text file named months.txt on which various deletion operations would be performed.

Method 1: Deleting a line using a specific position

In this method, the text file is read line by line using readlines(). If a line has a position similar to the position to be deleted, it is not written in the newly created text file. 

Example:

Python3




# deleting a line
# based on the position
 
# opening the file in
# reading mode
 
try:
    with open('months.txt', 'r') as fr:
        # reading line by line
        lines = fr.readlines()
         
        # pointer for position
        ptr = 1
     
        # opening in writing mode
        with open('months.txt', 'w') as fw:
            for line in lines:
               
                # we want to remove 5th line
                if ptr != 5:
                    fw.write(line)
                ptr += 1
    print("Deleted")
     
except:
    print("Oops! something error")


Output:

Deleted

‘5-May’ was written on the 5th line which has been removed as shown below:

Method 2: Deleting a line using a text that matches exactly with the line

In this method, after reading the file, each line is checked if it matches with the given text exactly. If it does not match, then it is written in a new file.

Python3




# deleting a line on the basis
# of a matching text (exactly)
 
# we want to remove a line
# with text = '8-August'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_2.txt', 'w') as fw:
            for line in lines:
               
                # strip() is used to remove '\n'
                # present at the end of each line
                if line.strip('\n') != '8-August':
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")


Output:

Deleted

The line having ‘8-August’ exactly has been removed as shown: 

Method 3: Using custom-made logics

Example 1: Deleting lines containing a specified pattern

Here, the lines containing the specified string pattern are removed. The pattern may not be necessarily the whole exact line.

Python3




# deleting a line matching
# a specific pattern or
# containing a specific string
 
# we want to delete a line
# containing string = 'ber'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_3.txt', 'w') as fw:
            for line in lines:
               
                # find() returns -1
                # if no match found
                if line.find('ber') == -1:
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")


Output:

Deleted

All the lines containing the pattern ‘ber’ such as ‘9-September’, ’10-October’, ’11-November’, ’12-December’ have been removed.

Example 2: Deleting lines with the condition

If we have a condition that the lines in our file must have a minimum length. So, the following example shows how to delete lines not having a minimum specified length.

Python3




# deleting all the lines that are
# not having the minimum length
# excluding the newline '\n' character
 
# let the min_len = 7
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        min_len = 7
 
        with open('months_4.txt', 'w') as fw:
            for line in lines:
                if len(line.strip('\n')) >= min_len:
                    fw.write(line)
 
    print("Deleted")
except:
    print("Oops! something error")


Output:

Deleted

All the lines not having a length of greater than or equal to 7 have been removed:



Previous Article
Next Article

Similar Reads

Python Program to Replace Specific Line in File
In this article, we are going to write a Python program to replace specific lines in the file. We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after that, we open the file in write-only mode and write
2 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Method 1: R
7 min read
How to Delete a Specific Row from SQLite Table using Python ?
In this article, we will discuss how to delete of a specific row from the SQLite table using Python. In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in
3 min read
Python program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer science portal User choice = 0 Output: geek a is This
2 min read
Compare two Files line by line in Python
In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation. Files in use: file.txt file1.txt Method 1: Using
3 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
Retrieve A Specific Element In a Csv File using Python
We have given a file and our task is to retrieve a specific element in a CSV file using Python. In this article, we will see some generally used methods for retrieving a specific element in a CSV file. Retrieve a Specific Element in a CSV File Using PythonBelow are some of the ways by which we can retrieve a specific element in a CSV file using Pyt
2 min read
PyQtGraph - Setting Symbol of Line in Line Graph
In this article we will see how we can set symbols of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A li
3 min read
PyQtGraph - Setting Shadow Pen of Line in Line Graph
In this article, we will see how we can set shadow pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
3 min read
three90RightbarBannerImg