Python: create a file object from a string

Advertisements

TLDR: How to create in Python a file object (preferably a io.TextIOWrapper, but anything with a readline() and a close() method would probably do) from a string ? I would like something like

f = textiowrapper_from_string("Hello\n")
s = f.readline()
f.close()
print(s)

to return "Hello".

Motivation: I have to modify an existing Python program as follows: the program stores a list (used as a stack) of file objects (more precisely, io.TextIOWrapper‘s) that it can "pop" from and then read line-by-line:

f = files[-1]
line = f.readline()
...
files.pop().close()

The change I need to do is that sometimes, I need to push into the stack a string, and I want to be able to keep the other parts of the program unchanged, that is, I would like to add a line like:

files.append(textiowrapper_from_string("Hello\n"))

Or maybe there is another method, allowing minimal changes on the existing program ?

>Solution :

There’s io.StringIO:

from io import StringIO

files.append(StringIO("Hello\n"))

Leave a ReplyCancel reply