Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

deleting a line from a file in python

Asked by Bernadette Bond Apr 17, 2021 816 views 1 answer
Share

About this question

How 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?

Your answer

1 Answer

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.