0

For example there's with statement:

with open("ACCELEROMETER", 'w') as ACCELEROMETER,\
    open('GPS', 'w') as GPS,\
    open('LIGHT', 'w') as LIGHT,\
    open('LOCATION', 'w') as LOCATION,\
    open('MIC', 'w') as MIC,\
    open('SCREEN', 'w') as SCREEN,\
    open('TIME', 'w') as TIME:

I want to get file objects just created using some python code : I'm looking for equivalent of dir function for local scope of with. Is it possible?

rok
  • 9,403
  • 17
  • 70
  • 126
  • 1
    huh? What do you want to do here ... do you want a list `[ACCELEROMETER, GPS, LIGHT, ...]`? And why do you want that? Perhaps a different approach would be more appropriate. – mgilson Dec 05 '13 at 08:37

1 Answers1

4

What you're asking for isn't really possible (without making some assumptions) since with doesn't create a new namespace. You could create a file-list object which is implemented as a context manager ...

class FileList(list):
    def __init__(self, files, mode='r'):
        list.__init__(open(arg, mode) for arg in files)
    def __enter__(self):
        return self
    def __exit__(self, *args):
        for fobj in self:
            fobj.close()

with FileList(["ACCELEROMETER", "GPS", ...], mode='w') as fl:
    for fobj in fl:
        ...
mgilson
  • 300,191
  • 65
  • 633
  • 696