2

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.

jleahy
  • 16,149
  • 6
  • 47
  • 66
H.Choi
  • 3,095
  • 7
  • 26
  • 24
  • Check if the `grep` program is available on your system. Because `grep -v` prints all non-matching lines from the input. – Roland Smith Aug 15 '12 at 12:14
  • possible duplicate of [i want to remove lines that contain certain string](http://stackoverflow.com/questions/11968998/i-want-to-remove-lines-that-contain-certain-string) – sloth Aug 16 '12 at 11:02

2 Answers2

3

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2
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   
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 4
    Simply do f2.write(x). New-line characters are a part of x already. Also strip() removes white-space which may not be desired. Another fix: open('out.txt', 'w'). Also this code requires python 2.7. – Yevgen Yampolskiy Aug 15 '12 at 03:49