Refactored slightly:
import csv
from sys import stdout
#output = "temp.txt"
output = "stdout"
with (open(output, "w") if output != 'stdout' else stdout) as file:
writer = csv.writer(file)
writer.writerow(["A","B","C"])
works on Python 3.6, at least.
But... this will close stdout after the with block completes.
For example:
with (open(output, "w") if output != 'stdout' else stdout) as file:
writer = csv.writer(file)
writer.writerow(["A","B","C"])
print("AFTER") # Raises "ValueError: I/O operation on closed file."
I think the best approach is just to handle the file closing directly. You do lose the benefit of the context manager auto-closing the file on exceptions, but without doing some additional work creating a pseduo-stdout that doesn't actually close on __exit__
, your best bet might be:
import csv
from sys import stdout
#output = "temp.txt"
output = "stdout"
file = (open(output, "w") if output != 'stdout' else stdout)
writer = csv.writer(file)
writer.writerow(["A","B","C"])
if output != "stdout": file.close()
print("AFTER")