我想要定義一個類方法直接寫入文件而不顯式關閉文件。但是,如果我回到喜歡的對象,因此:如何在我自己的類中使用`open`方法?
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()
,這將是一個很好的解決方法?
這可能有所幫助:http://effbot.org/zone/python-with-statement.htm – mshsayem
感謝您的鏈接。事實上,它揭示了這個問題... – LarsVegas