从多个文件读取行

2024-10-01 17:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件:

答:

John
Kevin
Richard

乙:

^{pr2}$

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

输出:

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

我试着用上下文库.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包,但没用。在


Tags: 文件richardnamesisaswithjobsmanager
3条回答

你基本上想要这样:

# 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 f:
    name = f.readlines()

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

roles = zip(name, job)

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

^{2}$

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

您可以使用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

这段代码适用于python3。如果您正在使用python2,请使用itertools.izip()。在

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

相关问题 更多 >

    热门问题