将输出的txt文件行与另一个txt文件连接起来。蟒蛇

时间:2018-05-31 02:53:55

标签: python

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

file1.txt:

Hello how are u?:

NYC: 

Coffee Shop:

File2.txt

Jhon 

WDC 

Starbucks

输出应为:

file3.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()

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

2 个答案:

答案 0 :(得分:0)

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

#!/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
$

答案 1 :(得分:0)

file1和file2中的所有行都包含' \ n'在末尾。使用strip()删除它: out=file1[j].strip()+":"+file2[j]