For each line in fileX I n开发者_C百科eed to scan all lines of fileY.
I tried this:
for line in fileinput.input('fileX'):
do.fun.stuff(line)
for element in fileinput.input('fileY'):
process(element,line)
But I get:
RuntimeError: input() already active
I guess I have to specify that the second instance of fileinput is different from the first one.
This doesn't work since fileinput.input()
creates a global instance, so you can't call it twice in the manner that you're trying to.
Why not simply:
for line in open('fileX'):
do.fun.stuff(line)
for element in open('fileY'):
process(element,line)
Here is the explicit answer to the solution suggested by @CatPlusPlus:
import fileinput
fileX = fileinput.FileInput(files='fileX')
fileY = fileinput.FileInput(files='fileY')
for line in fileX:
do.fun.stuff(line)
for element in fileY:
process(element,line)
fileinput.input
uses a global shared instance of fileinput.FileInput
. Use that class directly, creating two instances, and it should work.
Using fileinput, you can iterate over multiple files easily as a unit, but it doesn't seem to gain you anything here. Iterate over the contents of the files separately. One nice approach is using itertools.product
:
import itertools
with open('fileX', 'r') as f1:
with open('fileY', 'r') as f2:
for (line, element) in itertools.product(f1, f2):
process(element, line)
精彩评论