Reputation:
Suppose i have two files , having data
table1.txt contents
avvd, 1234, ufgh
klpn, 5678, oppr
srtv, 9abc, pxyz
table2.txt contents
abcd, 1234, efgh
klmn, 5678, opqr
stuv, 9abc, wxyz
Now I want to get merge them , because their second column is same , and show the result.
Desired output is if table1.txt and table2.txt columns are same then merge both tables and make them one and show them in output
avvd, 1234, ufgh, abcd, efgh
klpn, 5678, oppr, klmn, opqr
srtv, 9abc, pxyz, stuv, wxyz
Upvotes: 1
Views: 3129
Reputation: 4487
#input
file1 = open('1.txt', 'r')
file2 = open('2.txt', 'r')
matrix1 = [line.rstrip().split(', ') for line in file1.readlines()]
matrix2 = [line.rstrip().split(', ') for line in file2.readlines()]
file1.close()
file2.close()
#combine
t_matrix1 = [[r[col] for r in matrix1] for col in range(len(matrix1[0]))]
t_matrix2 = [[r[col] for r in matrix2] for col in range(len(matrix2[0]))]
final_t_matrix = []
for i in (t_matrix1 + t_matrix2):
if i not in final_t_matrix:
final_t_matrix.append(i)
final_matrix = [[r[col] for r in final_t_matrix] for col in range(len(final_t_matrix[0]))]
#output
outfile = open('out.txt', 'w')
for i in final_matrix:
for j in i[:-1]:
outfile.write(j+', ')
outfile.write(i[-1]+'\n')
outfile.close()
Upvotes: 1