Here is my file1:
agadfad
sdffasdf
Element 1, 0, 0, 0
Pcom
Element 2
Here is my file2:
PBAR
Element 1, 100, 200, 300, 400
Element 2
Continue...
I want to search with a keyword, "Element 1" in file1, if found store the whole line; then search in file2, if found at some line, replace it with the data from file1 which is in this case "Element 1,0,0,0". Similarly, if there are more keywords like "Element 2, Element 3 and so on...", and the files are very big, it should do the same (But this part comes later). I tried following code:
index1 = 0index2 = 0path1 = "C:\Users\sony\Desktop\BDF1.TXT"path2 = "C:\Users\sony\Desktop\BDF2.TXT"Target = 'Element 1'with open(path1) as f1:list1 = f1.readlines()for line in list1:index1 = index1 + 1if Target in line:print "Match Found at line %d" %(index)else:print "No Match Found in the target file!"with open(path2, "r+") as f2:list2 = f2.readlines()for line2 in list2:index2 = index2 + 1if Target in line2:list2[index2] = line + ' \n'else:print "No match found in the targetorg file!"f2.writelines(list2)
I am getting some output which looks like this:
PBAR
Element 1, 100, 200, 300, 400
Element 2
Continue... PBAR
Element 1, 100, 200, 300, 400
agadfad
Continue...
And i am also getting error list assignment index out of range
at somewhere line 20. It seems easier, but having hard time to figure it out.