問題描述
我有兩個文件,我想對它們執(zhí)行一些逐行操作.(換句話說,每個文件的第一行是對應(yīng)的,第二行也是如此,等等.)現(xiàn)在,我可以想到一些稍微麻煩的方法來同時遍歷兩個文件.然而,這是 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.
換句話說,有沒有一些簡單的方法來適應(yīng)
In other words, is there some simple way to adapt the
for line in file:
以便同時從兩個文件中提取數(shù)據(jù)?
so that it pulls data from both files simultaneously?
推薦答案
Python 2:
使用 itertools.izip
加入兩個迭代器.
Use itertools.izip
to join the two iterators.
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
.
在 Python 3 中,請改用 zip
和 zip_longest
.此外,使用 with
打開文件,這樣即使出現(xiàn)錯誤,也會自動處理關(guān)閉.
In Python 3, use zip
and zip_longest
instead. Also, use a with
to open files, so that closing is handled automatically even in case of errors.
with open(file1name) as file1, open(file2name) as file2:
for line1, line2 in zip(file1, file2):
#do stuff
這篇關(guān)于如何同時遍歷兩個文件中的行?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!