垂直拼接制表符分隔的txt文件
input1、input2 和 output 是用制表符分隔的文本文件。
如果 input1 是
a b c
1 2 3
而 input2 是
e r t
那么我希望 output 是
a b c
1 2 3
e r t
我尝试过用 Python 来合并文件,参考了 Python 合并文本文件 的内容。
我尝试了
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)
然后又尝试了
filenames = ['input1.txt', 'input2.txt']
import fileinput
with open('output.txt', 'w') as fout:
for line in fileinput.input(filenames):
fout.write(line)
但是这两个代码都是横向合并文件,而不是纵向合并。
这些代码生成了:
a b c
1 2 3e r t
2 个回答
1
你需要使用 \n
来换行。可以试试下面的代码示例,
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")
4
你输入的文件有个问题,就是最后一行没有换行符。换句话说,最后一行后面没有空行。所以你需要手动加上这个换行符:
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')