-2

I am trying to open a file and search for a particular string in a line and replace it with another string.

I am trying the following code.

def myFunct(file, test, patter, replace):
    with open(file, mode='r') as f:
        for line in f.readline():
            if str(line).__contains__(test):
                if patter in line:
                    print("Found here\n")
                    print(line)
    f.close()

The code does not seem to go into the for loop. Any suggestions ?

I have also tried a similar solution with the same problem.

Find and Replace

Community
  • 1
  • 1
Ram
  • 367
  • 1
  • 5
  • 12

1 Answers1

0

You are only reading the first line and iterate over the single characters of that line. You have to remove the readline:

def myFunct(file, test, patter, replace):
    with open(file, mode='r') as f:
        for line in f:
            if test in line and patter in line:
                print("Found here\n")
                print(line)
Daniel
  • 40,885
  • 4
  • 53
  • 79
  • I have tried the update you mentioned but i am having the same problem. The code just does not seem to enter the for loop. – Ram Sep 23 '15 at 06:11