input1,input2,output是制表符分隔的txt文件。
如果input1是
a b c
1 2 3
和input2是
e r t
然后我希望输出
a b c
1 2 3
e r t
我试图通过学习Python concatenate text files
来使用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
答案 0 :(得分: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')
答案 1 :(得分: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")