Find line number of replaced key value

Question:

How do I get the line number of replaced key value?
currently functions are different for it, how do i combine it to have line number at the time of replacing the string.

filedata= is a path of file. In which i need to replace strings.

old_new_dict = {'hi':'bye','old':'new'}

def replace_oc(file):
    lines = file.readlines()

    line_number = None
    for i, line in enumerate(lines):
        line_number = i + 1
        break
    return line_number

def replacee(path, pattern):
    for key, value in old_new_dict.items():
        if key in filedata:
            print("there")
            filedata = filedata.replace(key, value)
        else:
            print("not there")
Asked By: pkk

||

Answers:

You could break down the filedata into lines to check for the words to replace before doing the actual replacements. For example:

filedata = """The quick brown fox
jumped over
the lazy dogs
and the cow ran away 
from the fox"""

old_new_dict = {"dogs":"cats", "crazy":"sleeping","fox":"cow"}

for key,value in old_new_dict.items():
    lines = [i for i,line in enumerate(filedata.split("n"),1) if key in line]
    if lines:
        filedata = filedata.replace(key,value)
        print(key,"found at lines",*lines)
        
    else:
        print(key,"is not there")

output:

# dogs found at lines 3
# crazy is not there
# fox found at lines 1 5

print(filedata)

The quick brown cow
jumped over
the lazy cats
and the cow ran away 
from the cow
Answered By: Alain T.