如何同时迭代两个文件中的行? [英] How to iterate across lines in two files simultaneously?
问题描述
我有两个文件,我想在两个文件中执行一些按行操作。 (换句话说,每个文件的第一行对应,第二行等等)现在,我可以想到一些稍微麻烦的方法来同时迭代这两个文件; 然而,这是Python,所以我想有一些句法简写。
I have two files, and I want to perform some line-wise operation across both of them. (In other words, the first lines of each file correspond, as do the second, etc.) Now, I can think of a number of slightly cumbersome ways to iterate across both files simultaneously; however, this is Python, so I imagine that there is some syntactic shorthand.
换句话说,是否有一些简单的方法来适应
In other words, is there some simple way to adapt the
for line in file:
这样它可以同时从两个文件中提取数据吗?
so that it pulls data from both files simultaneously?
推荐答案
使用 itertools.izip
加入两个迭代器。
from itertools import izip
for line_from_file_1, line_from_file_2 in izip(open(file_1), open(file_2)):
如果文件是不等长,使用 izip_longest
。
If the files are of unequal length, use izip_longest
.
这篇关于如何同时迭代两个文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!