我是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:
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.
∏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
答案 0 :(得分: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
答案 1 :(得分:1)
你可以用这个:
className
答案 2 :(得分:1)
您可以使用上下文管理器:
import contextlib
@contextlib.contextmanager
def aline(outfile, *files):
final_data = zip(open(files[0]), open(files[1]))
yield ['\n'.join([a, b]) for a, b in final_data]
f = open(outfile, 'w')
for a, b in final_data:
f.write('\n'.join([a, b])+'\n\n')
f.close()
with aline('output.txt', *['data/data.txt', 'data/data2.txt']) as f:
print(f)
输出(int output.txt
):
feel my cold hands.
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.
I love oranges.
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.
Mexico has a large surplus of oil.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.
Ink stains don't rub out.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.
答案 3 :(得分:-1)
试试这个:
filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile,ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
for lines in zip(*files):
outfile.writelines(lines)
这种方法可以使用任意数量的输入文件。