94

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

134

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)
Sign up to request clarification or add additional context in comments.

4 Comments

On Windows, this results in an extra carriage return character after each row.
You can give the csv.writer constructor a lineterminator option:writer = csv.writer(sys.stdout, lineterminator=os.linesep)
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.
To be clear, there seems to be no way to use the lineterminator option (or property of a custom Dialect subclass) cause the writer to write only a linefeed and not Cr+Lf when running on Windows. That results in CrCrLf when writing through sys.stdout unless Python was run with universal linefeeds disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.