从多个文件中读取行

时间:2015-02-12 17:19:02

标签: python multiple-files readlines

我有两个文件:

A:

John
Kevin
Richard

B:

Manager
Salesperson
Doctor

我正在尝试同时读取这两个文件中的行并打印以下内容:

输出:

John is a Manager
Kevin is a Salesperson
Richard is a Doctor

我尝试使用contextlib.izip包但它无效。

代码:

with open('name') as names:
        with open('job') as jobs:
                for names1 in names:
                        jobs1 = jobs.readlines()
                        print names1 + jobs1

但是这会抛出错误

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

我也尝试过使用contextlib包但它没有用。

3 个答案:

答案 0 :(得分:4)

您可以使用zip函数和多个上下文管理器执行此操作:

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

此代码适用于Python 3.如果您使用的是Python 2,请使用itertools.izip()

此处发布的其他解决方案利用readlines()工作,但他们使用了不必要的内存量。当你关心的只是一对一行时,没有必要读入两个完整的文件,所以我强烈推荐我在这里描述的迭代器方法。

答案 1 :(得分:0)

你基本上想要这个:

# 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))

答案 2 :(得分:0)

您可以单独阅读这两个文件,然后压缩结果

with open('name') as f:
    name = f.readlines()

with open('job') as f:
    job = f.readlines()

roles = zip(name, job)

或者,您可以在代码中显示嵌套循环。问题出在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))

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