3

我想定义一个类方法来直接写入文件而不显式关闭文件。但是,如果我像这样返回对象:

class sqlBuilder(object):
    ...   

    def save_sql_stat(self, file_n, mode = 'w'):
        try:
            with open(file_n, mode) as sql_out:
                return sql_out

        except IOError, IOe:
            print str(IOe)

我将无法做到:

t = sqlBuilder(table)
out = t.save_sql_stat(sql_file)
out.write(...)

因为我要得到一个ValueError. 不打电话有什么好的解决方法out.close()

4

1 回答 1

5

您可以使用closingfromcontextlib并将with语句移到外部...

from contextlib import closing

def save_sql_stat(self, file_n, mode='w'):
    try:
        return closing(open(file_n, mode))
    except IOError as e:
        print e.message

sql = SqlBuilder()
with sql.save_sql_stat('testing.sql') as sql_out:
    pass # whatever
于 2012-10-01T09:02:48.200 回答