首页 > 解决方案 > 将 txt 文件的行与输出连接到另一个 txt 文件。Python

问题描述

我是 Python 新手,我试图将一个 file1.txt 的行与另一个 file2.txt 连接起来,它的输出必须是另一个 file3.txt 例如:

文件 1.txt:

Hello how are u?:

NYC: 

Coffee Shop:

文件2.txt

Jhon 

WDC 

Starbucks

输出应该是:

文件 3.txt:

Hello how are u?: Jhon 

NYC: WDC

Coffe Shop: Starbucks

我有这个:

 from io import open
 input1=open("file1.txt","r",encoding="utf-8")
 input2=open("file2.txt","r",encoding="utf-8")
 output=open("file3.txt","w",encoding="utf-8")

 file1=input1.readlines()
 file2=input2.readlines()

 j=0
 for i in ingles:
    out=file1[j]+":"+file2[j]
    j=j+1
    output.writelines(out)

input1.close()
input2.close()
output.close()

它创建文件,但不会将结果连接在同一行中......

标签: python

解决方案


此实现处理不等行长度的文件。

#!/usr/bin/python

from __future__ import print_function

FILE_A = './file1.txt'
FILE_B = './file2.txt'
OUTPUT = './file3.txt'

with open(FILE_A, 'r') as file_a, open(FILE_B, 'r') as file_b:
    with open(OUTPUT, 'w') as out:
        for a, b in map(None, file_a.readlines(), file_b.readlines()):
            a = a.rstrip() if a is not None else ''
            b = b.rstrip() if b is not None else ''
            print('%s%s' % (a, b), file=out)

用法:

第一个文件的内容
$ cat file1.txt
Hello how are u?:

NYC:

Coffee Shop:
foo
第二个文件的内容
$ cat file2.txt
Jhon

WDC

Starbucks
执行脚本
$ python concatenate.py
输出文件的内容
$ cat file3.txt
Hello how are u?:Jhon

NYC:WDC

Coffee Shop:Starbucks
foo
$

推荐阅读