How to write CSV output to stdout?
34,882
sys.stdout
is a file object corresponding to the program's standard output. You can use its write()
method. Note that it's probably not necessary to use the with
statement, because stdout
does not have to be opened or closed.
So, if you need to create a csv.writer
object, you can just say:
import sys
spamwriter = csv.writer(sys.stdout)
Related videos on Youtube
Author by
jsf80238
Married, two kids, two dogs, full-time computer-related job, house in a kinda-suburban area. I'm only missing the white picket fence.
Updated on July 05, 2022Comments
-
jsf80238 almost 2 years
I know I can write a CSV file with something like:
with open('some.csv', 'w', newline='') as f:
How would I instead write that output to
stdout
? -
Tyler Crompton about 5 yearsOn Windows, this results in an extra carriage return character after each row.
-
Brendan Quinn about 5 yearsYou can give the csv.writer constructor a lineterminator option:
writer = csv.writer(sys.stdout, lineterminator=os.linesep)
-
Solomon Duskis over 3 years
lineterminator=os.linesep
makes no sense, as on Windows this is no-op. You probably meantlineterminator='\n'
, which is also NOT an obviously correct solution (see comments on this post). Reconfiguring sys.stdout to disable universal newlines handling is a possible alternative.