2013-01-11 42 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 
相关问题