按顺序迭代两个文件中的行

时间:2012-07-24 07:37:14

标签: python

我有两个文件,我想在它们之间执行一些逐行操作(逐个)。我现在使用两个循环来实现这一目标。有没有办法在单个循环中进行(在python 2.7中):

for fileName in [fileNam1,fileName2]:
    for line in open(fileName):
        do something

5 个答案:

答案 0 :(得分:7)

正如已经指出itertools.chain是一个选项,但是还有另一个有用的标准模块,它避免了必须明确使用open ......

import fileinput
for line in fileinput.input(['file1.txt', 'file2.txt']):
    print line

这也有一些方便的行号和文件名等功能...查看http://docs.python.org/library/fileinput.html

上的文档

回复评论 - 与上下文管理器一起使用

from contextlib import closing

with closing(fileinput.input(['file1.txt', 'file2.txt'])) as infiles:
    for line in infiles:
        pass # stuff

答案 1 :(得分:4)

itertools模块有一个工具。试试这个:

import itertools

for line in itertools.chain(open(file_name1), open(file_name2)):
    # do something

答案 2 :(得分:4)

不完全是您的要求,但fileinput模块可能很有用。

"""Helper class to quickly write a loop over all standard input files.

Typical use is:

    import fileinput
    for line in fileinput.input():
        process(line)

This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty.  If a filename is '-' it
is also replaced by sys.stdin.  To specify an alternative list of
filenames, pass it as the argument to input().  A single file name is
also allowed.

Functions filename(), lineno() return the filename and cumulative line
number of the line that has just been read; filelineno() returns its
line number in the current file; isfirstline() returns true iff the
line just read is the first line of its file; isstdin() returns true
iff the line was read from sys.stdin.  Function nextfile() closes the
current file so that the next iteration will read the first line from
the next file (if any); lines not read from the file will not count
towards the cumulative line count; the filename is not changed until
after the first line of the next file has been read.  Function close()
closes the sequence.
...

答案 3 :(得分:0)

也许你可以使用列表理解或map,reduce,filter等来避免内循环。这完全取决于你的需要。你想做什么?

答案 4 :(得分:0)

这是我的第一个答案,所以请对不起任何错误

>>> file1 = open('H:\\file-1.txt')
>>> file2 = open('H:\\file-2.txt')
>>> for i, j in map(None, file1.readlines(), file2.readlines()):
        print i,j