【问题标题】:how to use `with open` in my own class method?如何在我自己的类方法中使用`with open`?
【发布时间】:2012-09-22 02:48:32
【问题描述】:

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

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(),有什么好的解决方法?

【问题讨论】:

标签: python methods file-handling


【解决方案1】:

您可以使用contextlib 中的closing 并将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

【讨论】:

  • 这就是我要找的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2016-04-11
  • 2020-01-30
  • 1970-01-01
  • 2011-05-13
相关资源
最近更新 更多