
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Complete Guide to Python StringIO Module with Examples
Sometimes we need data to be created or read in memory instead of actual files seen by the OS. This is where the Python StringIO module, an in-memory file-like object, comes into play. Read through this article to get a detailed explanation about the Python StringIO module.
What is Python StringIO Module?
Python StringIO module is an in-memory file-like object which can be used as both input and output to most of the functions expecting a standard file object. In other words, the file-like object acts like a regular file allowing most of the standard file I/O operations.
One of the important differences between them is that regular files are visible to the OS whereas file objects are created in memory and hence can be handled more efficiently.
Installing the StringIO Module
StringIO module is included in the IO module of the Python standard library, and we can use the below command to import it ?
from io import StringIO
Creating StringIO streams/file Objects
We can create a StringIO stream or file objects by passing a string to StringIO() module. Let's understand it with below given example ?
from io import StringIO String_doc = "Welcome to Tutorialspoint." Object_string = StringIO(String_doc)
In the above example we have created a StringIO object named Object_string by passing string-type String_doc.
Reading Data from StringIO Object
We can use read() function to read data from StringIO object. Below are given few relevant lines of code ?
Example
print(Object_string.read())
Output
The output will be ?
Welcome to Tutorialspoint.
Writing Data to StringIO Object
We can use write() function to write data to StringIO object. Below are given few relevant lines of code ?
Example
Object_string.write(" The website is www.tutorialspoint.com.") # making sure stream/file objcet is read from beginning Object_string.seek(0) print(Object_string.read())
Output
The output will be ?
Welcome to Tutorialspoint. The website is www.tutorialspoint.com.
Important Methods of StringIO
Some of the important methods of StringIO along with example codes are given below ?
StringIO.getvalue()
As the name implies, this function returns the entire content of the file. Here is the syntax of this function ?
File_name.getvalue()
Example
from io import StringIO # An arbitrary string Object_string ="Welcome to TutorialsPoint." # Using the StringIO method to set as file object file_module = StringIO(Object_string) # Retrieving the entire content of the file print(file_module.getvalue())
Output
It will produce the following output ?
Welcome to TutorialsPoint.
StringIO.seek()
This function is used to set the cursor position on the file. Once you perform any read and write operations, the cursor is set on the last index. Now to move the cursor at starting index of the file, we can use seek() function.
Here is the syntax of seek() function ?
File_name.seek(argument)
Here the argument will tell the function where to set the cursor position.
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # Reading the file print(file_module.read()) # But now if you want to read from the file again, # it will show empty file because the cursor is # set to the last index of the file. # The below code will return an empty string and does not print anything. print(file_module.read()) # Now to set the cursor position at start and to read/write file again, # we can use the seek() function. We need to pass argument as well. file_module.seek(0) # Now we can read the file again print(file_module.read())
Output
The above example will give the following output ?
Welcome to TutorialsPoint.
StringIO.truncate()
As the name implies, this function resizes the size of the file stream. It drops the file after the given index and saves it as well.
Here is the syntax of truncate() function ?
File_name.truncate(size = None)
You can provide the size from where it will truncate the file.
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # Reading the file print(file_module.read()) # Now set the cursor at 0. file_module.seek(0) # Now we will drop the file after index 10. file_module.truncate(10) # Now we can read the file again after truncating print(file_module.read())
Output
It will produce the following output ?
Welcome to TutorialsPoint. Welcome to
StringIO.tell()
This function tells us the current cursor position of the file. Given below is the syntax of tell() function ?
File_name.tell()
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # The current cursor position is at 0 print(file_module.tell()) # Now set the cursor at 10. file_module.seek(10) # Print the index of cursor print(file_module.tell())
Output
It will produce the following output ?
0 10
StringIO.close()
This function close the file and once applied, we cannot perform any further operations on that file. If you try to perform any operation, it will raise a ValueError.
Here is the syntax of close() function ?
File_name.close()
Example
# Importing the StringIO module from io import StringIO # An arbitrary string Object_string ="Welcome to TutorialsPoint." # Using the StringIO method to set as file object file_module = StringIO(Object_string) # Reading the file print(file_module.read()) # Closing the file file_module.close() # Let's try to read the file again print(file_module.read())
Output
It will produce the following output ?
Welcome to TutorialsPoint. ----------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-3c3241cbedca> in <module> 10 file_module.close() 11 # Reading the file ---> 12 print(file_module.read()) ValueError: I/O operation on closed file
StringIO Functions of Boolean Return Type
Here we will discuss some StringIO methods returning Boolean values i.e., True or False ?
StringIO.isatty()
This Boolean function will return True if the file object is interactive otherwise returns False. Here is the syntax of isatty() function ?
File_name.isatty()
Example
# Importing the StringIO module from io import StringIO # An arbitrary string Object_string ="Welcome to TutorialsPoint." # Using the StringIO method to set as file object file_module = StringIO(Object_string) # It will return True if file is interactive # and False if the file is not interactive. print("Is the file object interactive?", file_module.isatty())
Output
It will produce the following output ?
Is the file stream interactive? False
StringIO.readable()
This Boolean function will return True if the file object is readable and returns False if the file object is not readable. Below is the syntax of readable() function ?
File_name.readable()
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # It will return True if file is readable and # False if the file is not readable. print("Is the file readable?", file_module.readable())
Output
It will produce the following output ?
Is the file readable? True
StringIO.writable()
This Boolean function will return True if the file object is writeable and returns False if the file object is not writeable.
Here is the syntax of writable() function ?
File_name.writable()
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # It will return True if file is writeable and # False if the file is not writeable. print("Is the file writable?", file_module.writable())
Output
It will produce the following output ?
Is the file writable? True
StringIO.seekable()
This Boolean function will return True if the file object supports random access and returns False if the file object does not support random access.
Here is the syntax of seekable() function ?
File_name.seekable()
Example
from io import StringIO Object_string ="Welcome to TutorialsPoint." file_module = StringIO(Object_string) # It will return True if the file object supports random access and # False if the file object does not support random access. print("Is the file seekable?", file_module.seekable())
Output
It will produce the following output ?
Is the file seekable? True
StringIO.closed
This Boolean function will return True if the file object is closed and returns False if the file object is open.
Example
# Importing the StringIO module from io import StringIO # An arbitrary string Object_string ="Welcome to TutorialsPoint." # Using the StringIO method to set as file object file_module = StringIO(Object_string) # It will return True if file object supports random access # and False if the file object does not support random access. print("Is the file closed?", file_module.closed)
Output
It will produce the following output ?
Is the file closed? False
Conclusion
We have learned the StringIO module in Python which is a useful tool for working with string-based input and output streams. It allows us to create a file-like object that can be used as an input or output to various functions, and can be easily read from or written to using the write() and read() methods.
One of the main benefits of using StringIO is that it allows you to work with strings in a similar way to how you would work with files. This can be especially useful when you need to read from or write to a string, but do not want to create a temporary file on disk.
Another advantage of StringIO is that it is very efficient, as it stores the data in memory rather than on disk. This can make it faster than using a physical file, especially for small amounts of data.
Overall, StringIO is a useful and efficient tool for working with string-based input and output streams in Python. It is easy to use and can be a convenient alternative to working with physical files. We also understood several use cases where the Python StringIO module and its methods handle file streams effectively.