python - 如何在我自己的类方法中使用 `with open`?

标签 python methods file-handling

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

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

最佳答案

您可以使用 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

关于python - 如何在我自己的类方法中使用 `with open`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670138/

相关文章:

c# - 静态方法中的变量是否会自动变为静态,因为它们在 c# 中的静态范围内?

c - 如何在c中搜索文本文件中的特定字符串

r - 从R中的URL读取.txt文件时出错

python - Tensorflow 使用上一次迭代的值计算指标的 update_op

python - 使用 Python 读取网站上的每一行

java - 如何让我的程序执行随机方法?

C - 使用文件处理和链表登录

python - 在 Tkinter 的 Canvas 中显示比例值

python - 如何打印 float 的全精度 [Python]

c# - 在 C# 中,如何将某些方法调用完全排除在代码库之外?