match elements from two files, how to write the intended format to a new file

Posted by user2489612 on Stack Overflow See other posts from Stack Overflow or by user2489612
Published on 2014-05-31T04:07:37Z Indexed on 2014/05/31 15:27 UTC
Read the original article Hit count: 268

Filed under:

I am trying to update my text file by matching the first column to another updated file's first column, after match it, it will update the old file. Here is my old file:

Name Chr Pos ind1 in2 in3 ind4
foot 1 5 aa bb cc
ford 3 9 bb cc 00
fake 3 13 dd ee ff
fool 1 5 ee ff gg
fork 1 3 ff gg ee

Here is the new file:

Name Chr Pos
foot 1 5
fool 2 5
fork 2 6
ford 3 9
fake 3 13

The updated file will be like:

Name Chr Pos ind1 in2 in3 ind4
foot 1 5 aa bb cc
fool 2 5 ee ff gg
fork 2 6 ff gg ee
ford 3 9 bb cc 00
fake 3 13 dd ee ff 

Here is my code:

#!/usr/bin/env python

import sys
inputfile_1 = sys.argv[1]
inputfile_2 = sys.argv[2]
outputfile = sys.argv[3]

inputfile1 = open(inputfile_1, 'r')
inputfile2 = open(inputfile_2, 'r')
outputfile = open(outputfile, 'w')

ind = inputfile1.readlines()
cm = inputfile2.readlines()[1:]

outputfile.write(ind[0]) #add header

for i in ind:        
    i = i.split()
    for j in cm:
        j = j.split()
        if j[0] == i[0]:
            outputfile.writelines(j[0:3] + i[3:])
inputfile1.close()
inputfile2.close()
outputfile.close()

When I ran it, it returned a single column rather than the format i wanted, any suggestions? Thanks!

© Stack Overflow or respective owner

Related posts about python-2.7