StringIO Module in Python
Last Updated :
12 Jun, 2025
StringIO is a module in Python that allows you to treat strings as file-like objects. It provides an in-memory stream for text I/O (input/output), which means you can read from and write to a string just like you would with a file, but without disk I/O. To use StringIO, you need to import it from the io module:
from io import StringIO
Example:
Python
from io import StringIO
s = 'This is initial string.'
f = StringIO(s) # StringIO object
print(f.read())
f.write(" Welcome to GeeksForGeeks.")
f.seek(0)
print(f.read())
OutputThis is initial string.
This is initial string. Welcome to GeeksForGeeks.
Explanation:
- f.read() reads from the current cursor to the end, moving the cursor to the end after reading.
- f.write(" Welcome to GeeksForGeeks.") appends the new string at the current cursor position (end of the stream).
- f.seek(0) moves the cursor back to the beginning of the stream.
- f.read() reads the full content from the start, printing the combined text.
StringIO methods and functions
1. getvalue(): This method returns the entire contents of the StringIO object as a single string. It is helpful when you want to retrieve all the text you’ve written to the stream.
Python
from io import StringIO
f = StringIO("Hello and welcome to GeeksForGeeks.")
print(f.getvalue())
OutputHello and welcome to GeeksForGeeks.
Explanation: This code creates a StringIO text stream initialized with a string and prints its entire content using getvalue().
2. Boolean utility functions: These are functions that returns either True or False. They are used to check specific properties or conditions of an object like readability, writability, etc. Let’s understand the following boolean utility functions with the help of the table below:
Function | Description | Returns |
---|
isatty() | Checks if the stream is interactive | False (always) |
---|
readable() | Checks if the stream can be read | True |
---|
writable() | Checks if the stream supports writing | True |
---|
seekable() | Checks if the stream allows moving the cursor | True |
---|
closed | Checks if the stream is closed | True or False |
---|
Python
from io import StringIO
f = StringIO("Sample")
print(f.isatty())
print(f.readable())
print(f.writable())
print(f.seekable())
print(f.closed)
OutputFalse
True
True
True
False
Explanation: This code creates a StringIO text stream and uses boolean functions to check and print whether the stream is interactive, readable, writable, seekable or closed.
3. seek(position): This method allows you to move the internal cursor to a specific position within the stream. It is necessary if you want to read or write from a particular point.
Python
from io import StringIO
f = StringIO("Hello")
print(f.read())
print(f.read())
f.seek(0)
print(f.read())
Explanation: This code creates a StringIO stream with "Hello", reads and prints it. The second read prints nothing as the cursor is at the end. After seek(0), it reads and prints the content again.
4. truncate(size=None): This method resizes the stream. If a size is provided, the stream is cut off after that many characters. If no size is provided, it truncates the stream at the current cursor position.
Python
from io import StringIO
f = StringIO("Hello and welcome")
f.seek(0)
f.truncate(10)
f.seek(0)
print(f.read())
Explanation: This code creates a StringIO stream, truncates its content to 10 characters, resets the cursor and prints the truncated content.
5. tell(): This method returns the current position of the cursor in the stream. It helps you keep track of where you are reading or writing.
Python
from io import StringIO
f = StringIO("Python")
print(f.tell())
f.read(3)
print(f.tell())
Explanation: This code creates a StringIO stream with "Python" and prints the initial cursor position (0). It then reads 3 characters, moves the cursor and prints the new position (3).
6. close(): This method closes the stream. Once the stream is closed, you can no longer read from or write to it and attempting to do so will raise an error.
Python
from io import StringIO
f = StringIO("Python")
f.close()
print(f.closed)
Explanation: This code creates a StringIO stream with "Python", closes the stream and then prints whether the stream is closed .
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