我有两个文件:
答:
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 包,但没有成功。
最佳答案
您可以使用 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()
的解决方案可以工作,但它们使用了不必要的内存量。当您一次只关心一对行时,无需读取两个完整文件,因此我强烈推荐使用我在此处描述的迭代器方法。
关于python - 从多个文件读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28483768/