with open('myfile.txt') as f:
for line in f:
doSomething(line)
有没有办法一次迭代两个文件?这里有一些伪代码可以帮助您理解..
with open('myfile.txt') as f: and with open ('myfile2.txt') as d:
for line in f and for line2 in d:
doSomething(line, line2)
答案 0 :(得分:4)
with open('myfile.txt') as f, open('myfile2.txt') as d:
for line1, line2 in zip(f, d):
do_something(line1, line2)
请注意,对于Python 2,您应该使用itertools.izip
- 它一次只在内存中保存一对行,而不是返回所有行对的列表。