python - 使用 python 将两个文件中的每一行连接为一行

标签 python string join

我正在尝试使用 python 将两个文件的行连接为一个。谁能帮我解决这个问题:

文件 1:

abc|123|apple

abc|456|orange

abc|123|grape

abc|123|pineapple

abc|123|mango

文件 2:

boise

idaho

sydney

tokyo

london

预期输出文件:

abc|123|apple|boise
abc|456|orange|idaho
abc|123|grape|sydney
abc|123|pineapple|tokyo
abc|123|mango|london

**Code tried so far:**

    from itertools import izip
    with open('merged.txt', 'w') as res:
            with open('input1.txt') as f1:
                    with open('input2.txt') as f2:
                            for line1, line2 in zip(f1, f2):
                                    res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))

我是 python 新手,有没有一种简单的方法可以使用分隔符“|”附加两个文件中的行。提前致谢。

最佳答案

非常接近,只需将最后一行更改为:

res.write("{0}|{1}\n".format(line1.rstrip(), line2.rstrip()))

关于python - 使用 python 将两个文件中的每一行连接为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862802/

相关文章:

mysql - JOINS 而不是子选择

python - 如何在 Scrapy/Twisted 中使用线程,即如何在响应回调中对阻塞代码进行异步调用?

python - 如何在使用 matplotlib 的情况下使用 pyinstaller

string - Scala/Spark 高效的部分字符串匹配

android - 从资源中获取 android 字符串数组中的数据

mysql - 在sql中使用内连接创建表

python - 在 ubuntu 14.04(trusty tahr) 上构建 Pylucene

python - 改进在前景蒙版中遇到分割对象时的背景减除

string - 条件绑定(bind)的初始化程序必须具有 Optional 类型,而不是 HTTPCookieStorage 上的 'String'

sql - 连接三张表,主表在中间