The Wayback Machine - https://web.archive.org/web/20241127022039/https://www.geeksforgeeks.org/python-program-to-delete-specific-line-from-file/
Open In App

Python Program to Delete Specific Line from File

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

Python
# 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.

Python
# 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.

Python
# 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.

Python
# 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
Python provides built-in functions for creating, writing, and reading files. Two types of files 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. Example [GFGTABS] Python # Open the file in read mode with open('filename.
5 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
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
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
Python Program to Get the File Name From the File Path
In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path.  Better to have knowledge of: Python OS-modulePython path moduleRegular expressionsBuilt in rsplit()Method 1: Python OS-moduleExam
6 min read
Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types.   Full reversing: In this type of reversing all the content gets reversed.  Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last positi
2 min read
How to import excel file and find a specific column using Pandas?
To read specific columns from an Excel file in Pandas, you have the flexibility to use either column indices or letters. This is achieved by setting the usecols argument, which can take a comma-separated string or a list containing column identifying letters or indices. In this article, we will learn how to import an Excel file into a data frame an
5 min read
Export Specific Columns in DataFrame to CSV File
A data frame is a tabular data structure similar to a spreadsheet. It has rows and columns. CSV (Comma-Separated Values) is a plain text file format used for storing tabular data. Each line in a CSV file represents a row of data, and the values within a line are separated by commas. This article explores two methods for exporting selected columns f
3 min read
How to delete data from file in Python
When we no longer require data, we usually prefer to erase or delete it so that space can be used up by other data that is important to us. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Refer to the below articles to get the idea ab
3 min read
How to delete a CSV file in Python?
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Approach : Import module.Check the path of the file.
2 min read
How to delete from a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that
3 min read
Delete pages from a PDF file in Python
In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the possibility of data processing inside Programming
4 min read
Python Delete File
When any large program is created, usually there are small files that we need to create to store some data that is needed for the large programs. when our program is completed, so we need to delete them. In this article, we will see how to delete a file in Python. Methods to Delete a File in Python Python Delete File using os. removeDelete file in
4 min read
Delete a directory or file using Python
In this article, we will cover how to delete (remove) files and directories in Python. Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Table of Content Using the os.remove() MethodDelete a FileRemove file with absolute pathCheck if File Exists Before DeletingUsing
6 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
PyQtGraph - Setting Pen of Line in Line Graph
In this article we will see how we can set 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, etc.) A li
4 min read
PyQtGraph - Setting Alpha Value of Line in Line Graph
In this article we will see how we can set alpha value 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
4 min read
PyQtGraph - Clearing the Line in Line Graph
In this article, we will see how we can clear the line of line graph in 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 line c
3 min read
PyQtGraph - Getting Data Bounds of the Line in Line Graph
In this article we will see how we can get data bounds of the line of line graph in 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
4 min read
PyQtGraph - Getting Data of Line in Line Graph
In this article we will see how we can get data of the line of line graph in 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 l
3 min read
PyQtGraph - Getting Name of Line in Line Graph
In this article we will see how we can get name of the line of line graph in 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 l
4 min read
PyQtGraph - Setting Symbol Pen of Line in Line Graph
In this article we will see how we can set symbol pen 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
4 min read
PyQtGraph - Setting Symbol Size of Line in Line Graph
In this article we will see how we can set symbol size 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.)
4 min read
PyQtGraph - Getting Pixel Padding of Line in Line Graph
In this article we will see how we can get pixel padding of the line of line graph in 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,
4 min read
PyQtGraph - Setting Symbol Brush of Line in Line Graph
In this article we will see how we can set symbols brush 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.
3 min read
three90RightbarBannerImg