Yes, an opened file should be closed. But I am missing something.
You want to write and read a text in a file object which you would print() it in another case?
Why don't you write a function that is just 'opening' and closing a file and you can use another one to do the job?
You want to write and read a text in a file object which you would print() it in another case?
Why don't you write a function that is just 'opening' and closing a file and you can use another one to do the job?
In [1]: import io In [2]: def io_handler(text, callback): # stupid name but my English.... :D ...: f = io.StringIO() ...: callback(text, f) ...: f.getvalue() ...: f.close() ...: In [3]: def say(text, file): ...: print(text, file=file) ...: In [4]: io_handler("Does it work? Will see", say) In [5]: def io_handler(text, callback): ...: f = io.StringIO() ...: callback(text, f) ...: print(f.getvalue()) ...: f.close() ...: In [6]: io_handler("Does it work? Will see", say) Does it work? Will see