Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Testing Output to stdout
Next article icon

sys.stdout.write in Python

Last Updated : 11 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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) 

Output
Hello, 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') 

Output
Python 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

output.txt file

Explanation:

  • 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-countdown

dynamic countdown

Explanation:

  • \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



Next Article
Python | Testing Output to stdout

V

vanshikagoyal43
Improve
Article Tags :
  • Python
  • Python-sys
Practice Tags :
  • python

Similar Reads

  • Python - sys.stdout.flush()
    A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a c
    3 min read
  • Writing to file in Python
    Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail. Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following t
    4 min read
  • turtle.write() function in Python
    turtle module in Python provides a way to create graphics and animations using Tkinter. The turtle.write() method is used to display text at the turtle’s current position on the canvas. This function helps in labeling graphics, adding instructions or displaying values dynamically. It allows both obj
    3 min read
  • Python - Write Bytes to File
    Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file c
    2 min read
  • Python | Testing Output to stdout
    Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to p
    2 min read
  • How to write Comments in Python3?
    Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and mai
    4 min read
  • time.sleep() in Python
    Python time sleep() function suspends execution for the given number of seconds. Syntax of time sleep() Syntax : sleep(sec) Parameters : sec : Number of seconds for which the code is required to be stopped. Returns : VOID. Sometimes, there is a need to halt the flow of the program so that several ot
    4 min read
  • How to write to an HTML file in Python ?
    Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file. We can save any amount of our input data into an HTML file in python using the following examples in t
    2 min read
  • Traceback in Python
    Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when
    8 min read
  • How to use sys.argv in Python
    In Python, sys.argv is used to handle command-line arguments passed to a script during execution. These arguments are stored in a list-like object, where the first element (sys.argv[0]) is the name of the script itself and the rest are arguments provided by the user. This feature is helpful when you
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences