-4

i want search 'banana' word and replace line in file

for example

test.txt

"test tes apple tt estsetse setse tse banana tes test setset orange sets et setset sets etst"

search 'banana' and change line

'setse tse banana tes test'-> 'i like banana'

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 5
    I'm guessing this is your homework; If you don't start writing programs yourself, you've failed your class already! Start by reading the file line by line and see what it prints out. Use a "find" type of function to see if the line contains "banana" etc. – Boop Sep 03 '14 at 07:23

2 Answers2

2

It is very simple...

please consider this code...

fp = open('D://source.txt',"r+")

fg = open('D://target.txt',"w")

for line in fp:

    if line.find("banana") != -1:
        new_line = line.replace(line,"i like banana\n")
        fg.write(new_line)

    else:
        fg.write(line)

fg.close()

fp.close()
W1ll1amvl
  • 1,219
  • 2
  • 16
  • 30
2

You can also use this example:

lookup = 'banana'
with open(text.txt) as myFile:
  for num, line in enumerate(myFile, 1):
    if lookup in line:
       # do some work
       break # if the work is finished
    elif not lookup in line:
       # do smtg else
       pass
myFile.close()
Guillaume
  • 2,752
  • 5
  • 27
  • 42