问题
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')
?
回答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')
来源:https://stackoverflow.com/questions/24936955/python-vertical-txt-concatenation-not-working-properly