sys.stdout.write in Python
Last Updated :
11 Apr, 2025
sys.stdout.write() is a built-in Python method that writes output directly to the console without automatically adding a newline (\n). It is part of the sys module and requires import sys before use.
Unlike print(), it does not insert spaces between multiple arguments, allowing precise control over text formatting. It returns the number of characters written instead of None. Example:
Python
import sys
sys.stdout.write("Hello, ")
sys.stdout.write("World!")
res = sys.stdout.write("Gfg") # Capturing return value
print("\nReturn Value:", res)
OutputHello, World!Gfg
Return Value: 3
Explanation:
- sys.stdout.write("Hello, ") writes "Hello, " without moving to a new line.
- sys.stdout.write("World!") continues on the same line.
- sys.stdout.write("Gfg") appends "Gfg" and returns 3, the number of characters written. Finally, print("\nReturn Value:", res) moves to a new line.
Syntax of sys.stdout.write
sys.stdout.write("string")
Parameters:
- string: The text that will be written to the standard output.
Return Value: It returns the number of characters written. In interactive mode, this value may be displayed because the interpreter echoes function return values.
Examples of sys.stdout.write
Example 1: Use sys.stdout.write() in a loop
This example demonstrate how to print elements of a list on the same line and then on separate lines using sys.stdout.
Python
import sys
var = sys.stdout
s = ['Python', 'is', 'awesome']
# Print on the same line
for e in s:
var.write(e + ' ')
var.write('\n') # New line
# Print each element on a new line
for e in s:
var.write(e + '\n')
OutputPython is awesome
Python
is
awesome
Explanation: sys.stdout.write() prints list elements on the same line using a space and then on separate lines with \n. This avoids automatic spaces or newlines from print().
Example 2: Redirect output to a file
A useful feature of sys.stdout is that it can be reassigned, allowing us to redirect output to a file instead of displaying it on the console. This is particularly helpful for logging and storing program results.
Python
import sys
with open('output.txt', 'w') as file:
sys.stdout = file # Redirect output to file
print('Geeks for geeks')
sys.stdout = sys.__stdout__ # Restore stdout
Output
output.txt fileExplanation:
- Temporarily redirect sys.stdout to a file object.
- Any standard output (like print()) is then written to the file.
- After writing, we restore the original sys.stdout to resume console output.
Example 3: Create a dynamic countdown
This example shows how to use sys.stdout.write() to dynamically update text on the same line, it's useful for countdowns or progress bars.
Python
import sys
import time
for i in range(5, 0, -1):
sys.stdout.write(f'\rCountdown: {i} ')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\nTime's up!\n") # Use double quotes to avoid conflict with the apostrophe
Output
dynamic countdownExplanation:
- \r (carriage return) moves the cursor to the start of the line.
- sys.stdout.flush() ensures the text is immediately printed.
- time.sleep(1) adds a one-second delay between updates.
- Finally, we print “Time’s up!” on a new line.
To read about more Python's built in methods, refer to Python's Built In Methods
Difference between print() and sys.stdout.write()
Understanding this difference is important for precise output control, especially in scenarios like dynamic console updates, logging or writing to files. It helps in optimizing performance, avoiding unnecessary formatting and ensuring the desired output structure in various programming tasks.
Feature | print() | sys.stdout.write() |
---|
Auto newline | Yes (print() adds \n by default) | No (must manually add \n if needed) |
---|
Output Formatting | Supports sep and end parameters | No additional formatting options |
---|
Returns | None | Number of characters written |
---|
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read