0

There are two solutions from Concatenate tab-delimited txt files vertically

Suppose input1 is

X\tY

input2 is

A\tB\r\n
C\t\r\n

Here, A, B, C are ordinary words and \t is tab.

If I run

filenames = [input1, input2]
with open(output, 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read().rstrip() + '\n')

then I get

X\tY\r\n
A\tB\r\n
C

Suddenly \t after C disappears.

If I run

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

then I get

X\tY\r\n
A\tB\r\n
C\t\r\n
\r\n

I simply want to concatenate vertically. In this case, I would need this.

X\tY\r\n
A\tB\r\n
C\t\r\n

I used these two files as example inputs.

https://drive.google.com/file/d/0B1sEqo7wNB1-M3FJS21UTk02Z1k/edit?usp=sharing

https://drive.google.com/file/d/0B1sEqo7wNB1-eWxiTmhKVTJrNjQ/edit?usp=sharing

@pavel_form

Do you mean I have to code

filenames = [input1, input2]
with open(output, 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read().rstrip('\r\n') + '\n')

?

Community
  • 1
  • 1
user3123767
  • 1,115
  • 3
  • 13
  • 22

1 Answers1

1

Your first example will work if you add parameter "what chars to strip" in rstrip call. Like this:

    outfile.write(infile.read().rstrip('\r\n') + '\n')

So, the complete example will be:

    filenames = [input1, input2]
    with open(output, 'w') as outfile:
        for fname in filenames:
            with open(fname) as infile:
                outfile.write(infile.read().rstrip('\r\n') + '\n')
pavel_form
  • 1,760
  • 13
  • 14
  • I tested the version I wrote on my revised question, and it works. To clarify and confirm, I edited my question to ask you if what I understood is correct. – user3123767 Jul 24 '14 at 16:54
  • Yes, thats what I meant. Will update answer to contain complete example. – pavel_form Jul 24 '14 at 16:55