85

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
jsf80238
  • 1,577
  • 2
  • 11
  • 24

1 Answers1

121

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)
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • 1
    On Windows, this results in an extra carriage return character after each row. – Tyler Crompton Mar 08 '19 at 21:55
  • 4
    You can give the csv.writer constructor a lineterminator option:`writer = csv.writer(sys.stdout, lineterminator=os.linesep)` – Brendan Quinn Apr 03 '19 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](https://stackoverflow.com/a/17725590/1026)). [Reconfiguring sys.stdout to disable universal newlines handling](https://stackoverflow.com/a/34997357/1026) is a possible alternative. – Nickolay Oct 17 '20 at 12:56