September 2026
1051 pages
35h 4m
English
The io module of the standard library contains the StringIO class, which provides the interface of a file object, but internally operates on a string.
This is useful, for example, if a function expects an open file object as a parameter to write to, but you would rather have the written data in the form of a string. Usually a StringIO instance can be passed here so that the written data can be reused as a string afterward:
>>> from io import StringIO>>> pseudofile = StringIO()
The constructor can optionally be passed a string containing the initial contents of the file. From now on, the returned instance referenced by pseudofile can be used like a file object:
>>> pseudofile.write("Hello world" ...
Read now
Unlock full access