如何同时遍历两个文件中的行?

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?

推荐答案

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 中,请改用 zipzip_longest.此外,使用 with 打开文件,这样即使出现错误,也会自动处理关闭.

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

这篇关于如何同时遍历两个文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)