How to remove the line where a specific string is found in a .txt file?

Question:

import os

word_to_replace, replacement_word = "", ""                                                     

if (os.path.isfile('data_association/names.txt')):
    word_file_path = 'data_association/names.txt'
else:
    open('data_association/names.txt', "w")
    word_file_path = 'data_association/names.txt'

word = "Claudio"

with open(word_file_path) as f:
    lineas = [linea.strip() for linea in f.readlines()]
    numero = None
    if word in lineas: numero = lineas.index(word)+1

    if numero != None:
        #Here you must remove the line with the name of that file
    else: print(That person's name could not be found within the file, so no line has been removed)

I need to try to remove that name from the following .txt file (assuming that there is a line with that name in that file, if it is a file without that line it should print that that name has not been found and that it cannot be deleted)

Lucy
Samuel
María del Pilar
Claudia
Claudio
Katherine
Maríne

After removing the line with the example name "Claudio", the file would look like this:

Lucy
Samuel
María del Pilar
Claudia
Katherine
Maríne

PS: this list of names is a reduced fragment of the actual list, so it’s better if instead of rewriting the whole file, you just edit the specific line where that name was found

Answers:

Here is one way you can remove a specific line from a text file that contains a given string in

Python:

import os
word_to_replace = "Claudio"
word_file_path = 'data_association/names.txt'

if os.path.isfile(word_file_path):
    with open(word_file_path, "r") as f:
        lines = f.readlines()
    with open(word_file_path, "w") as f:
        for line in lines:
            if word_to_replace not in line:
                f.write(line)
            else:
                print(f"Line containing '{word_to_replace}' removed.")
else:
    print("File not found.")

This code first checks if the specified file exists, if the file exists, it opens the file in read mode, reads all the lines into a list and then opens the file in write mode. It then iterates through the list of lines, writing each line to the file, except the line that contains the specified string (in this case "Claudio"). If the specified string is found in the line, it prints a message indicating that the line containing that string has been removed. If the file doesn’t exist, it will print a message "File not found."

Please note that this method will remove all the lines which contains that word.

Answered By: Bhaskar Gupta
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.