【问题标题】:Concatenate rows of txt files with output to another txt file. Python将 txt 文件的行与输出连接到另一个 txt 文件。 Python
【发布时间】:2018-05-31 02:53:54
【问题描述】:

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

file1.txt:

Hello how are u?:

NYC: 

Coffee Shop:

文件2.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()

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

【问题讨论】:

  • for i in ingles 应该做什么?

标签: python


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多