2012-07-24 39 views
3

两个文件我有两个文件,我想(一个接一个)跨均进行了一些行明智的操作。我现在使用两个循环来实现这一点。有没有办法做到在一个循环(在Python 2.7):迭代跨越线路中的序列

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

回答

7

正如已指出itertools.chain是一种选择,但也有其避免了明确地使用open另一个有用的标准模块...

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

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

在回复评论 - 与上下文管理

012使用
from contextlib import closing 

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

+1我喜欢这个更好,因为'itertools'解决方案会使它不方便关闭文件。 – jamylak 2012-07-24 07:51:44

+0

感谢您指出'fileinput'模块。 – imsc 2012-07-24 08:07:19

+0

如果程序突然结束,下次运行它时,会得到一个'RuntimeError:input()已激活'。有没有办法解决这个问题。 – imsc 2012-07-24 13:28:05

4

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

import itertools 

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

虽然您的解决方案做的工作,我选择'fileinput'解决方案,它看完后关闭该文件。不管怎么说,还是要谢谢你。 – imsc 2012-07-24 08:10:04

0

也许你可以使用列表理解或映射避免内环,减少,过滤器等,这一切都取决于你的需要。你想做什么?

+0

这些解决方案仍然会涉及循环,我会考虑更多的评论而不是答案。 – jamylak 2012-07-24 07:56:12

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. 
... 
+1

感谢您指出'fileinput'模块。 – imsc 2012-07-24 08:08:25

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 
+0

-1不是问题。还有'zip(* args)'''map(None,* args)'。不需要'readlines'。 'file'对象是通过文件行的迭代器,所以你可以简单地做:'zip(file1,file2)' – jamylak 2012-07-24 08:13:17