Search code examples
pythonpython-3.xstringfileconcatenation

Concatenate two txt files Python


I have two txt files, the first file contains strings separated by space, as follows:

M N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D A D G A Q A I Q L G A N H V W K L N G K P D D 
N T F S Q V W V F S D T P S R L P E L M N G A Q A L A N Q I N T F V L N D A D G A Q A I Q L G A N H V W K L N G K P D D R 

The second file contains strings of 0 and 1s, as follows:

0000000000000000000000000001000000000000000000000000000000000
0000000000010000000000000000000000000000000000000000000000000

I want to get a new file that join the first row of file1 with the first row of file2 and so on separated by TAB. How could I do that?

I have this function for reading the files.

with open("/home/darteagam/diploma/bert/files/bert_aa10.txt") as f1,open("/home/darteagam/diploma/bert/files/out_bert_10.txt") as f2:
    def read(f1,f2):
        for x in f1:
            print(x)
        for y in f2:
            print(y)
    read(f1,f2)

Solution

  • Just zip the two.

    with open("/home/darteagam/diploma/bert/files/bert_aa10.txt") as f1,open("/home/darteagam/diploma/bert/files/out_bert_10.txt") as f2:
        for a,b in zip(f1,f2):
            print('\t'.join([a.strip(), b.strip()])
    

    As a side note, it's bad practice to embed full pathnames in your code. Some day, you will want to run this on some other computer where that path doesn't work You should manage your current directory so you can use simple file names or relative paths.