2013-01-11 41 views
-1

我有兩個文件,我想將它們的內容並排放入一個文件中,即輸出文件的第n行應該包含文件1的第n行,並且文件2的第n行。這些文件具有相同的行數。將文件內容加入到一個文件

我直到現在:

with open('test1.txt', 'r') as f1, open('test2.txt', 'r') as f2: 

    with open('joinfile.txt', 'w') as fout: 

     fout.write(f1+f2) 

,但它給出了一個錯誤說 -

TypeError: unsupported operand type(s) for +: 'file' and 'file' 

我在做什麼錯?

+4

您連接兩個文件對象,你不要」 t要 – avasal

+5

任何原因shell的'cat test1.txt test2.tx t> joinfile.txt'不符合你的需求? – eumiro

+0

@eumiro:一些窗戶沒有貓;) – georg

回答

1

你可以做到這一點:

fout.write(f1.read()) 
fout.write(f2.read()) 
+0

這給出了在線的第一個文件的內容。 –

+0

嗯,我用Python 2.7和Python 3.2測試了它,並且在'joinfile.txt'中獲得了兩個測試文件的內容。 –

1

您actualy串聯2個文件對象,但是,你要conctenate字符串。

首先用f.read讀取文件內容。例如,這種方式:

with open('test1.txt', 'r') as f1, open('test2.txt', 'r') as f2: 
    with open('joinfile.txt', 'w') as fout: 
    fout.write(f1.read()+f2.read()) 
2

我想嘗試itertools.chain()和每行的工作線(您使用「R」來打開你的文件,所以我想你不紅二進制文件:

from itertools import chain 

with open('test1.txt', 'r') as f1, open('test2.txt', 'r') as f2: 
    with open('joinfile.txt', 'w') as fout: 
     for line in chain(f1, f2): 
      fout.write(line) 

它可以作爲發電機,所以沒有記憶問題有可能,即使是大文件。

編輯

新reuqirements,新的山姆ple:

from itertools import izip_longest 

separator = " " 

with open('test1.txt', 'r') as f1, open('test2.txt', 'r') as f2: 
    with open('joinfile.txt', 'w') as fout: 
     for line1, line2 in izip_longest(f1, f2, fillvalue=""): 
      line1 = line1.rstrip("\n") 
      fout.write(line1 + separator + line2) 

我在行之間加了一個separator字符串。

izip_longest如果一個文件比另一個文件有更多的行,也可以工作。 fill_value ""然後用於缺失的行。 izip_longest也可用作發電機。

重要的是行line1 = line1.rstrip("\n"),我想這很明顯。

+0

它不會將第一個文件的行與第二個文件的第一行相連接。 –

+0

呵呵,所以你的文件有相同的行數,你想把'fout'的第n行像'f1'的第n行還是'f2'的第n行? –

+0

是的,它有相同的行數,我想加入一個文件的每一行與另一個文件 –

1

我寧願使用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 
相關問題