H.Choi
H.Choi

Reputation: 3223

how do i delete a line that contains a certain string?

What I am trying to do here is : 1.read lines from a text file. 2.find lines that contain certain string. 3.delete that line and write the result in a new text file.

For instance, if I have a text like this:

Starting text
How are you?
Nice to meet you
That meat is rare
Shake your body

And if my certain string is 'are' I want the output as:

Starting text
Nice to meet you
Shake your body

I don't want something like:

Starting text

Nice to meet you

Shake your body

I was trying something like this:

opentxt = open.('original.txt','w')
readtxt = opentxt.read()

result = readtxt.line.replace('are', '')

newtxt = open.('revised.txt','w')
newtxt.write(result)
newtxt.close()

But it don't seem to work...

Any suggestions? Any help would be great!

Thanks in advance.

Upvotes: 3

Views: 11476

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

with open('data.txt') as f,open('out.txt') as f2:
    for x in f:
        if 'are' not in x:
            f2.write(x.strip()+'\n')  #strip the line first and then add a '\n', 
                                      #so now you'll not get a empty line between two lines   

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799550

Same as always. Open source file, open destination file, only copy lines that you want from the source file into the destination file, close both files, rename destination file to source file.

Upvotes: 3

Related Questions