1

input1, input2, output are tab-delimited txt files.

If input1 is

a b c
1 2 3

and input2 is

e r t

then I would want output to be

a b c
1 2 3
e r t

I tried to concatenate files using python by learning from Python concatenate text files

I tried

filenames = ['input1.txt', 'input2.txt']
with open('output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

and then tried

filenames = ['input1.txt', 'input2.txt']
import fileinput
    with open('output.txt', 'w') as fout:
    for line in fileinput.input(filenames):
        fout.write(line)

But both codes concatenate files horizontally, not vertically.

The codes create this:

a b c
1 2 3e r t
Community
  • 1
  • 1
user3123767
  • 1,115
  • 3
  • 13
  • 22

2 Answers2

4

The problem of your input files is, that the last line is not terminated by a new-line-character. So you have to add it by hand:

filenames = ['input1.txt', 'input2.txt']
with open('output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read().rstrip() + '\n')
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • I explained my problem at http://stackoverflow.com/questions/24936955/python-vertical-txt-concatenation-not-working-properly Could you have a look at it? – user3123767 Jul 24 '14 at 14:48
1

You need to line break using \n. Try the following code sample,

filenames = ['input1.txt', 'input2.txt']
with open('output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)
        outfile.write("\n")
Leth0_
  • 544
  • 2
  • 6
  • 15