Using the with ... as construct is useful for automatically closing a file. This means that using it with sys.stdout , as you know, will crash your program because it will try to shut down the stdout system!
This means that something like with open(name, 'w') if name else sys.stdout as: will not work.
This makes me say that there is no easy and pleasant way to write your snippet better ... but there are probably better ways to think about how to build such code!
The main thing is to find out when you need to open (and, more importantly, close) the file handler for file_name when file_name exists.
Personally, I would just drop with .. as and take care to open the file - and, more importantly, close it! - somewhere else. The mileage for this may vary depending on how your software works.
This means that you can simply do:
out_file = open(file_name, 'w') if file_name else sys.stdout
and work with out_file in your program.
When you close, do not forget to check if there is a file or not :)
And have you thought about using the logging module? This makes it easy to add different handlers, print to a file, print to stdout ...
source share