Skip to main content
 首页 » 编程设计

Python之来自 2 个文件的行与\n

2025年05月04日14jackei

我是 Python 新手。我有两个文件,其中包含我需要将 2 个文件逐行组合成一个文件的句子。

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:  
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡. 
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ. 
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ. 
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ. 
 
 
 
FINAL OUTPUT should look like:  
 
feel my cold hands. 
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡. 
 
I love oranges.  
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ. 
 
Mexico has a large surplus of oil. 
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ. 
 
Ink stains don't rub out. 
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ. 

这是我尝试过的

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) 

这里的代码只是一个接一个地连接文件。但是,它不是逐行分割并创建\n。 谢谢!!

引用资料: combine multiple text files into one text file using python

Python concatenate text files

请您参考如下方法:

所以诀窍是我们想同时遍历两个文件。为此,我们可以像这样使用 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