88

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?

1 Answer 1

126

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)
3
  • 2
    On Windows, this results in an extra carriage return character after each row. Commented Mar 8, 2019 at 21:55
  • 4
    You can give the csv.writer constructor a lineterminator option:writer = csv.writer(sys.stdout, lineterminator=os.linesep) Commented Apr 3, 2019 at 12:25
  • 4
    lineterminator=os.linesep makes no sense, as on Windows this is no-op. You probably meant lineterminator='\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.
    – Nickolay
    Commented Oct 17, 2020 at 12:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.