兩個文件我有兩個文件,我想(一個接一個)跨均進行了一些行明智的操作。我現在使用兩個循環來實現這一點。有沒有辦法做到在一個循環(在Python 2.7):迭代跨越線路中的序列
for fileName in [fileNam1,fileName2]:
for line in open(fileName):
do something
兩個文件我有兩個文件,我想(一個接一個)跨均進行了一些行明智的操作。我現在使用兩個循環來實現這一點。有沒有辦法做到在一個循環(在Python 2.7):迭代跨越線路中的序列
for fileName in [fileNam1,fileName2]:
for line in open(fileName):
do something
正如已指出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
也許你可以使用列表理解或映射避免內環,減少,過濾器等,這一切都取決於你的需要。你想做什麼?
這些解決方案仍然會涉及循環,我會考慮更多的評論而不是答案。 – jamylak 2012-07-24 07:56:12
不正是你所要求的,但中的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. ...
感謝您指出'fileinput'模塊。 – imsc 2012-07-24 08:08:25
這是我的第一個回答,請對不起任何錯誤
>>> 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
-1不是問題。還有'zip(* args)'''map(None,* args)'。不需要'readlines'。 'file'對象是通過文件行的迭代器,所以你可以簡單地做:'zip(file1,file2)' – jamylak 2012-07-24 08:13:17
+1我喜歡這個更好,因爲'itertools'解決方案會使它不方便關閉文件。 – jamylak 2012-07-24 07:51:44
感謝您指出'fileinput'模塊。 – imsc 2012-07-24 08:07:19
如果程序突然結束,下次運行它時,會得到一個'RuntimeError:input()已激活'。有沒有辦法解決這個問題。 – imsc 2012-07-24 13:28:05