I always open and write into files using with
statement:
with open('file_path', 'w') as handle:
print >>handle, my_stuff
However, there is one instance where I need to be able to be more flexible, and write to sys.stdout
(or other types of streams), if that is provided instead of file path:
So, my question is this: Is there a way for using with
statement both with real files and with sys.stdout
?
Note that I can use the following code, but I think this defeats the purpose of using with
:
if file_path != None:
outputHandle = open(file_path, 'w')
else:
outputHandle = sys.stdout
with outputHandle as handle:
print >>handle, my_stuff
!=
withis not
. – Wrinkle