Merging data based on matching first column in Python : <p>I currently have two sets of data files that look like this:</p>

<p>File 1:</p>

<pre><code>test1 ba ab cd dh gf
test2 fa ab cd dh gf
test3 rt ty er wq ee
test4 er rt sf sd sa
</code></pre>

<p>and in file 2:</p>

<pre><code>test1 123 344 123
test1 234 567 787
test1 221 344 566
test3 456 121 677
</code></pre>

<p>I would like to combine the files based on mathching rows in the first column (so that "tests" match up)</p>

<p>like so:</p>

<pre><code>test1 ba ab cd dh gf 123 344 123
test1 ba ab cd dh gf 234 567 787
test1 ba ab cd dh gf 221 344 566
test3 rt ty er wq ee 456 121 677
</code></pre>

<p>I have this Code</p>

<pre><code>def combineFiles(file1,file2,outfile):
      def read_file(file):
         data = {}
         for line in csv.reader(file):
            data[line[0]] = line[1:]
         return data
      with open(file1, 'r') as f1, open(file2, 'r') as f2:
         data1 = read_file(f1)
         data2 = read_file(f2)
         with open(outfile, 'w') as out:
            wtr= csv.writer(out)
            for key in data1.keys():
               try:
                  wtr.writerow(((key), ','.join(data1[key]), ','.join(data2[key])))
               except KeyError:
                  pass
</code></pre>

<p>However the output ends up looking like this:</p>

<pre><code>test1 ba ab cd dh gf 123 344 123
test3 er rt sf sd sa 456 121 677
</code></pre>

<p>Can anyone help me with how to make the output so that test1 can be printed all three times?</p>

<p>Much Appreciated</p>
