开发者

Is there a way of nesting two fileinput in python?

开发者 https://www.devze.com 2023-04-12 16:48 出处:网络
For each line in fileX I n开发者_C百科eed to scan all lines of fileY. I tried this: for line in fileinput.input(\'fileX\'):

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

精彩评论

暂无评论...
验证码 换一张
取 消