Lar*_*gas 3 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)
Run Code Online (Sandbox Code Playgroud)
我将无法做到:
t = sqlBuilder(table)
out = t.save_sql_stat(sql_file)
out.write(...)
Run Code Online (Sandbox Code Playgroud)
因为我要得到一个ValueError.没有打电话会有什么好的解决方法out.close()?
您可以使用closing从contextlib与移动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
Run Code Online (Sandbox Code Playgroud)