-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
3
  • 1
    Please post one line from each file, and the corresponding desired line in the output file. What are the columns separated by? Commented Dec 30, 2014 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. Commented Dec 30, 2014 at 20:31
  • I haz a feeling that OP copy-pasted an email reply Commented Dec 30, 2014 at 20:33

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

@ali: this is exactly why I posted a comment for clarification on your original post. Please address that, without which I can't provide a super-accurate answer
@ali: I've updated my answer to be exactly what you need
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)

5 Comments

I like it, but this only works if OP's files are space delimited, which is similar to the assumption I made. The question really isn't super clear
@ Hackaholic my files are tab limited
gives this error: SyntaxError: invalid syntax and it is related to "," after f1
with open('fisrts.txt') as f1, open('eights.txt') as f2, open('outfile.txt','w') as out: ^ SyntaxError: invalid syntax
@ali check the next version of solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.