-2

I have 2 text files with the same number of rows, but there is no common column between my files. the first file has 9 columns and the 2nd one has 8 columns. both of them have 111557 rows. the order of rows in 2 files is the same, so I just want to simply merge them, which means I would have one text file with 17 columns.

This is the first column of the 1st .txt file (they are tab limited)

     chr1   HAVANA  gene    29554   31109   .   +   .

This is the 1st line of the 2nd .txt file(they are tab limited)

     ENSG00000243485.2  ENSG00000243485.2   lincRNA NOVEL   MIR1302-11  lincRNA NOVEL   MIR1302-11
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
ali
  • 51
  • 4
  • 1
    Please post one line from each file, and the corresponding desired line in the output file. What are the columns separated by? – inspectorG4dget Dec 30 '14 at 20:28
  • Ok, this is just too much. Did you try to google anything? Do you have any of your own code? Even a line to open a file? To read lines from the file? To write a line to a file? When you have those, we can talk. – bosnjak Dec 30 '14 at 20:31
  • I haz a feeling that OP [copy-pasted an email reply](http://stackoverflow.com/posts/27712062/revisions) – inspectorG4dget Dec 30 '14 at 20:33

2 Answers2

3
import csv

with open('path/to/file1') as infile1, open('path/to/file2') as infile2, open('path/to/output', 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    for row1,row2 in zip(csv.reader(infile1, delimiter='\t'), csv.reader(infile2, delimiter='\t')):
        writer.writerow(row1+row2)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

try like this:

with open('file1') as f1, open('file2') as f2, open('outfile','w') as out:
    for x in f1:
        y = next(f2)
        out.write("{}\t{}".format(x.strip(),y))

try like this if you getting error in above:

f1 = open('file1') 
f2 = open('file2')
out = open('outfile','w')
for x in f1:
    y = next(f2)
    out.write(x.strip() + "\t" + y)
Hackaholic
  • 19,069
  • 5
  • 54
  • 72