How to Delete Specific Line from a Text File in Python?

In this article, we will show you how to delete a specific line from a text file using Python. We'll explore different methods to accomplish this task with practical examples.

Assume we have a text file named TextFile.txt with the following content ?

Good Morning
This is Tutorials Point sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome everyone
Learn with a joy

Method 1: Using readlines() and write()

This approach reads all lines into memory, filters out the unwanted line, and rewrites the file ?

# Create sample file first
with open("TextFile.txt", "w") as f:
    f.write("Good Morning\n")
    f.write("This is Tutorials Point sample File\n") 
    f.write("Consisting of Specific\n")
    f.write("source codes in Python,Seaborn,Scala\n")
    f.write("Summary and Explanation\n")
    f.write("Welcome everyone\n")
    f.write("Learn with a joy\n")

# Delete specific line (line 2)
def delete_line(filename, line_to_delete):
    with open(filename, 'r') as file:
        lines = file.readlines()
    
    with open(filename, 'w') as file:
        for line_number, line in enumerate(lines, 1):
            if line_number != line_to_delete:
                file.write(line)
    
    print(f"Line {line_to_delete} deleted successfully")

# Delete line 2
delete_line("TextFile.txt", 2)

# Display updated content
print("File content after deletion:")
with open("TextFile.txt", "r") as file:
    print(file.read())
Line 2 deleted successfully
File content after deletion:
Good Morning
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome everyone
Learn with a joy

Method 2: Using List Comprehension

A more concise approach using list comprehension to filter lines ?

# Recreate sample file
with open("TextFile.txt", "w") as f:
    content = ["Good Morning\n", "This is Tutorials Point sample File\n", 
               "Consisting of Specific\n", "source codes in Python,Seaborn,Scala\n",
               "Summary and Explanation\n", "Welcome everyone\n", "Learn with a joy\n"]
    f.writelines(content)

def delete_line_compact(filename, line_to_delete):
    with open(filename, 'r') as file:
        lines = file.readlines()
    
    # Filter out the line to delete using list comprehension
    filtered_lines = [line for i, line in enumerate(lines, 1) if i != line_to_delete]
    
    with open(filename, 'w') as file:
        file.writelines(filtered_lines)

# Delete line 3
delete_line_compact("TextFile.txt", 3)

print("Updated file content:")
with open("TextFile.txt", "r") as file:
    for line_num, line in enumerate(file, 1):
        print(f"{line_num}: {line.strip()}")
Updated file content:
1: Good Morning
2: This is Tutorials Point sample File
3: source codes in Python,Seaborn,Scala
4: Summary and Explanation
5: Welcome everyone
6: Learn with a joy

Method 3: Using Temporary File

This safer approach uses a temporary file to avoid data loss if an error occurs ?

import tempfile
import os

# Recreate sample file
with open("TextFile.txt", "w") as f:
    content = ["Good Morning\n", "This is Tutorials Point sample File\n", 
               "Consisting of Specific\n", "source codes in Python,Seaborn,Scala\n",
               "Summary and Explanation\n", "Welcome everyone\n", "Learn with a joy\n"]
    f.writelines(content)

def delete_line_safe(filename, line_to_delete):
    # Create temporary file
    temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
    
    try:
        with open(filename, 'r') as original_file:
            for line_number, line in enumerate(original_file, 1):
                if line_number != line_to_delete:
                    temp_file.write(line)
        
        temp_file.close()
        
        # Replace original file with temporary file
        os.replace(temp_file.name, filename)
        print(f"Line {line_to_delete} deleted safely")
        
    except Exception as e:
        # Clean up temporary file if error occurs
        temp_file.close()
        os.unlink(temp_file.name)
        raise e

# Delete line 5
delete_line_safe("TextFile.txt", 5)

print("Final file content:")
with open("TextFile.txt", "r") as file:
    print(file.read())
Line 5 deleted safely
Final file content:
Good Morning
This is Tutorials Point sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Welcome everyone
Learn with a joy

Key Points

  • Line numbering: Python uses 0-based indexing, but users typically think in 1-based line numbers

  • Memory usage: readlines() loads the entire file into memory

  • Error handling: Always handle cases where the line number doesn't exist

  • File safety: Use temporary files for important data to prevent corruption

Comparison

Method Memory Usage Safety Best For
readlines() + write() High Low Small files
List comprehension High Low Concise code
Temporary file Low High Important data

Conclusion

Use the temporary file method for important data to prevent corruption. For small files, the simple readlines() approach works well. Always validate line numbers to avoid errors.

Updated on: 2026-03-26T21:19:04+05:30

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements