Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Printing to File Streams

print() normally prints to the <stdout> file stream. You can change this behavior using the file parameter. You can access the <stdout> stream directly from the sys library:

>>>
>>> import sys
>>> result = sys.stdout.write('hello\n')
hello
>>> result
6

You can also change where print() prints to:

with open('file.txt', mode='w') as file_object:
    print('hello world', file=file_object)

eshivaprasad on May 17, 2020

Are there situations in which sys.stdout.write() is preferable than print()?

Christopher Trudeau RP Team on May 19, 2020

Not commonly. There are a couple bizarre corner cases (later in the course I mock out print and then need to print something to screen), but these are rare and far between.

Become a Member to join the conversation.