Find Data From First File When Matched And Print In Next Line After Matched Line In File2
I have file1 as 1 AN3D3BWP210H6P51CNODSVT-(.A1(Y1),.A2(),.A3(),.Z(v1)); |2 2 BUFFSKFD32BWP210H6P51CNODSVT-(.I(v1),.Z(v2)); |3 3 GND2D1BWP210H6P51CNODSVT-(.A1(v2),.A2(),.ZN(v3)); |5
Solution 1:
Here's a solution which uses a list of strings to get around the temporary file issue. This will work fine so long as the number of replacement lines doesn't get too huge to hold in memory.
It also assumes that you wouldn't have a case where two adjacent lines from file2 match with the same line of file1, because the next(fout)
means that this next line won't be checked against file1.
import re
new_lines = []
withopen('file1','r') as fin:
for line in fin:
l=line[-5:]
l2=re.sub('^.*\((.*?)\)[^\(]*$','\g<1>',line) ### to find the value of last bracket
fout=open('file2','r')
# Store altered lines in a list of stringsfor line2 in fout:
k=line2[-5:]
if"()"in line2 and l==k:
try:
nextline = next(fout)
k=nextline.replace("()","("+l2+")",1)
new_lines.append(k)
except StopIteration: # Don't care if we reach end of file2pass
fout.close()
# Now write list of strings to filewithopen('file2', 'a') as fout:
fout.write("\n")
for line in new_lines:
fout.write(line)
Post a Comment for "Find Data From First File When Matched And Print In Next Line After Matched Line In File2"