Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

I want to delete a specific line containing a specific string in Python.

Ex-

Suppose I have a file fruit.txt having the following content:

Banana

Apple

Apple1

Grapes

Now, I want to delete Apple from that file and I have made this following function:

def deleteLine():

fname = 'fruit.txt'

f = open(fname)

output = []

for line in f:

    if not "Apple" in line:

        output.append(line)

f.close()

f = open(fname, 'w')

f.writelines(output)

f.close()

It gives this output;

Banana

Apple

So, the main problem is that the function is deleting both Apple and Apple1 but I only want to delete “Apple”.

The required should be like this:

Banana

Apple1

Grapes

How should I change my function so that it gives the correct output?

1 Answer

0 votes
by (25.1k points)

You need to open the file and read its contents in memory, then open the file again write the line to it but without the line you wish to omit:

e.g.:

with open("yourfile.txt", "r") as f:

    lines = f.readlines()

with open("yourfile.txt", "w") as f:

    for line in lines:

        if line.strip("\n") != "nickname_to_delete":

            f.write(line)

Wanna become an Expert in python? Come & join our Python Certification course

Related questions

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...