Python - 使用\n来配对来自2个文件的行

sha*_*arp 1 python python-3.x

我是Python的新手.我有两个文件,我需要将两个文件逐行合并到一个文件中.

file_1.txt: 
feel my cold hands.
I love oranges. 
Mexico has a large surplus of oil.
Ink stains don't rub out.

file_2.txt: 
?ª ¬? º’¿ª ¡ª ??¡Æ?¡.
??«¸ ?Ò«‡±‚?° ??¿ª ?Øæ??¨¥Ÿ.
????ƒ?ø°¥¬ ¥Ÿ?Æ¿« ø©?–¿« ºÆ¿Ø?° ¿÷¥Ÿ.
¿??© ¿?±?¿? ¥€æ?µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.



FINAL OUTPUT should look like: 

feel my cold hands.
?ª ¬? º’¿ª ¡ª ??¡Æ?¡.

I love oranges. 
??«¸ ?Ò«‡±‚?° ??¿ª ?Øæ??¨¥Ÿ.

Mexico has a large surplus of oil.
????ƒ?ø°¥¬ ¥Ÿ?Æ¿« ø©?–¿« ºÆ¿Ø?° ¿÷¥Ÿ.

Ink stains don't rub out.
¿??© ¿?±?¿? ¥€æ?µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.
Run Code Online (Sandbox Code Playgroud)

这是我试过的

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)
Run Code Online (Sandbox Code Playgroud)

这段代码只是一个接一个地汇编文件.但是,它并没有逐行削减并创建\n.谢谢!!

参考: 使用python将多个文本文件合并为一个文本文件

Python连接文本文件

FHT*_*ell 5

所以诀窍是我们想要同时迭代这两个文件.为此,我们可以zip像这样使用函数:

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
    with open(filenames[0]) as f1, open(filenames[1]) as f2:
        for f1_line, f2_line in zip(f1, f2):
            outfile.write(f1_line)
            outfile.write(f2_line)
            outfile.write("\n")  # add blank line between each pair
Run Code Online (Sandbox Code Playgroud)

  • 最后使用`outfile.write('\n')`以100%回答OP的问题. (2认同)