How can I flush the output of the print function in Python?

Better Stack Team
Updated on February 3, 2023

In Python, you can use the flush method of the sys.stdout object to flush the output of the print function. For example, you can use the following code to flush the output of the print function:

 
import sys
print("Hello, World!")
sys.stdout.flush()

You can also use the file parameter of the print function to specify where the output should be written. For example, you can use the following code to flush the output of the print function to a file:

 
import sys
with open('output.txt', 'w') as f:
    print("Hello, World!", file=f)

In python 3.3 and higher, you can also use the flush parameter of the print function to flush the output.

 
print("Hello, World!", flush=True)
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →