我宁愿使用shutil.copyfileobj。您可以轻松地将其与glob.glob在系统中,你可以结合来连接的模式
>>> import shutil
>>> infiles = ["test1.txt", "test2.txt"]
>>> with open("test.out","wb") as fout:
for fname in infiles:
with open(fname, "rb") as fin:
shutil.copyfileobj(fin, fout)
与glob.glob结合
>>> import glob
>>> with open("test.out","wb") as fout:
for fname in glob.glob("test*.txt"):
with open(fname, "rb") as fin:
shutil.copyfileobj(fin, fout)
除了以上说了一堆文件,如果你是使用posix应用程序,更喜欢使用它
D:\temp>cat test1.txt test2.txt > test.out
如果您使用的是Windows,则可以从命令提示符处发出以下命令。
D:\temp>copy/Y test1.txt+test2.txt test.out
test1.txt
test2.txt
1 file(s) copied.
注意 根据您最新的更新
Yes it has the same number of lines and I want to join every line of one file with the other file
with open("test.out","wb") as fout:
fout.writelines('\n'.join(''.join(map(str.strip, e))
for e in zip(*(open(fname) for fname in infiles))))
和POSIX系统上,你可以做
paste test1.txt test2.txt
您连接两个文件对象,你不要” t要 – avasal
任何原因shell的'cat test1.txt test2.tx t> joinfile.txt'不符合你的需求? – eumiro
@eumiro:一些窗户没有猫;) – georg