使用"在"范围内获取文件对象。块

时间:2013-12-05 08:35:54

标签: python 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:

我想获取刚刚使用一些python代码创建的文件对象: 我正在为的本地范围寻找等效的dir function。 有可能吗?

1 个答案:

答案 0 :(得分:4)

因为with没有创建新的命名空间,所以你要求的是不可能的(没有做出一些假设)。您可以创建一个文件列表对象,该对象实现为上下文管理器...

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:
        ...