I need to create a list of open image commands from an image list. I have to do it like that, instead of doing the "open image" inside a for because I need to pass to a function the data in this exact format.
Let me explain better.
This is the format that I have:
img_my_list=['img_1.png','img_2.png', 'img_3.png']
This is the format that i need for my function (I cannot use a for inside my function):
img_open_format_list = [(open(join(dirname(__file__), 'img_1.png'), 'rb'), 'image/png'),
(open(join(dirname(__file__), 'img_2.png'), 'rb'), 'image/png'),
(open(join(dirname(__file__), 'img_3.png'), 'rb'), 'image/png')]
How can I transform the list?
CodePudding user response:
Every open
should be accompanied by a close
unless used as a context manager.
The contextlib.ExitStack
is perfectly suited for that task.
from contextlib import ExitStack
img_my_list=['img_1.png','img_2.png', 'img_3.png']
with ExitStack() as stack:
images = [(stack.enter_context(open(img, 'rb')), 'image/png') for img in img_my_list]
... # do work
As you exit the scope, all opened images will be closed.
CodePudding user response:
I figure it out that it can be done with map
:
img_my_list = ['img_1.png','img_2.png', 'img_3.png']
img_open_command_list = map(lambda x: (open(x, 'rb'), 'image/png'), img_my_list)
This way I get the open command list that I desire by doing: list(img_open_command_list)
. And the images are attached perfectly in my report.