Python 从多个文件中读取行

Python 从多个文件中读取行,python,readlines,Python,Readlines,我有两个文件: A: B: 我试图同时从两个文件中读取行并打印以下内容: 输出: John is a Manager Kevin is a Salesperson Richard is a Doctor 我尝试使用contextlib.izip包,但它不起作用 代码: 但这也带来了错误 `TypeError: cannot concatenate 'str' and 'list' objects` 我还尝试使用contextlib软件包,但没有成功。您基本上希望这样: # These can

我有两个文件:

A:

B:

我试图同时从两个文件中读取行并打印以下内容:

输出:

John is a Manager
Kevin is a Salesperson
Richard is a Doctor
我尝试使用contextlib.izip包,但它不起作用

代码:

但这也带来了错误

`TypeError: cannot concatenate 'str' and 'list' objects`

我还尝试使用contextlib软件包,但没有成功。

您基本上希望这样:

# These can come from open("file").readlines()
a = ("John", "Kevin", "Richard")
b = ("Manager", "Salesperson", "Doctor")

for person, role in zip(a, b):
    print("{} is a {}".format(person, role))

你基本上想要这个:

# These can come from open("file").readlines()
a = ("John", "Kevin", "Richard")
b = ("Manager", "Salesperson", "Doctor")

for person, role in zip(a, b):
    print("{} is a {}".format(person, role))
您可以使用函数和多个上下文管理器来实现这一点:

with open('name') as name_file, open('job') as job_file:

    for name_line, job_line in zip(name_file, job_file):

        print("{} is a {}".format(
            name_line.strip(), job_line)) # don't forget to strip the newline 
                                          # from the names
这段代码适用于Python3。如果您使用的是Python 2,请使用

这里发布的其他解决方案利用了
readlines()
功能,但它们使用了不必要的内存量。当一次只需要读一对行时,不需要读入两个完整的文件,因此我强烈建议使用我在这里介绍的迭代器方法。

您可以使用函数和多个上下文管理器来实现这一点:

with open('name') as name_file, open('job') as job_file:

    for name_line, job_line in zip(name_file, job_file):

        print("{} is a {}".format(
            name_line.strip(), job_line)) # don't forget to strip the newline 
                                          # from the names
这段代码适用于Python3。如果您使用的是Python 2,请使用


这里发布的其他解决方案利用了
readlines()
功能,但它们使用了不必要的内存量。当一次只需要读一对行时,不需要读入两个完整的文件,因此我强烈推荐我在这里描述的迭代器方法。

您可以分别读取这两个文件,然后压缩结果

i、 e

或者,可以使用代码中显示的嵌套循环。问题出在
readlines()
,它将返回所有读取的行。然而,文件对象是python中的生成器,因此您可以简单地对其进行迭代

with open('name') as names:
    with open('job') as jobs:
        for n in names:
            for j in jobs:
                print("{n} is a {j}".format(n=n, j=j))

我更喜欢第一个选项,因为它更具可读性。

您可以分别读取这两个文件,然后压缩结果

i、 e

或者,可以使用代码中显示的嵌套循环。问题出在
readlines()
,它将返回所有读取的行。然而,文件对象是python中的生成器,因此您可以简单地对其进行迭代

with open('name') as names:
    with open('job') as jobs:
        for n in names:
            for j in jobs:
                print("{n} is a {j}".format(n=n, j=j))

我更喜欢第一个选项,因为它更具可读性。

不错!我不知道一个人可以像这样使用多个上下文。非常简洁!美好的我不知道一个人可以像这样使用多个上下文。非常简洁!可能的重复可能的重复
with open('name') as names:
    with open('job') as jobs:
        for n in names:
            for j in jobs:
                print("{n} is a {j}".format(n=n, j=j))