merging two tsv files

710 views
Skip to first unread message

yinx

unread,
Nov 20, 2015, 5:09:50 AM11/20/15
to Python GCU Forum
Hi!
I have two tsv files that I want to merge together. They have one column, the key, which is the same and I want to get the values of both files in one.
How do I do this? my code gives me this Type error: unsupported operand type(s) for +: 'collections.defaultdict' and 'collections.defaultdict'
This is the code that I have now.
Thanks in advance!

import csv
from collections import defaultdict
contig_map = defaultdict(list)
scaffold_map = defaultdict(list)

with open('file_one.txt', 'r') as file_one:
    csv_reader = csv.reader(file_one, delimiter = "\t")
    for row in csv_reader:
        contig_map[row[0]].append(row[-1])
   

with open('file_two.txt', 'r') as file_two:
    csv_reader = csv.reader(file_two, delimiter = "\t")
    for row in csv_reader:
        scaffold_map[row[0]].append(row[1:])
       
with open('merged_file', 'w') as out_file:
    merged = [contig_map + scaffold_map]
    d = {}
    for k in contig_map.iterkeys():
        d[k] = tuple(d[k] for d in merged)
   
print d

Robert Mandić

unread,
Nov 20, 2015, 6:17:38 AM11/20/15
to python-g...@googlegroups.com
If you only need to merge two files, you can just concatenate them together:

open('newfile.csv', 'w').write(open('f1.csv').read() + open('f2.csv').read())

--
You received this message because you are subscribed to the Google Groups "Python GCU Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-gcu-for...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Lp, Robert

yinx

unread,
Nov 20, 2015, 7:06:18 AM11/20/15
to Python GCU Forum
That doesn't work, it gives me a syntaxerror saying: SyntaxError: EOL while scanning string literal
Do you have other sugggestions or am i doing it wrong?

Op vrijdag 20 november 2015 12:17:38 UTC+1 schreef Robert Mandić:

Robert Mandić

unread,
Nov 20, 2015, 7:19:40 AM11/20/15
to python-g...@googlegroups.com

Nop.
This is pure python code.
Must work on version 2 and 3.

Reply all
Reply to author
Forward
0 new messages