我寧願使用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