-1

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 ?

user0
  • 185
  • 11
  • What was wrong with using an `io.TextIOWrapper`? – mkrieger1 May 20 '22 at 16:30
  • @mkrieger1: >>> import io >>> f = io.TextIOWrapper("Hello") Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'readable' – user0 May 20 '22 at 16:38
  • @mkrieger1: yes, thanks! This is also fsimonjetz's answer, which I accepted. It's strange that that question doet not appear on the "Related" list on the right. – user0 May 20 '22 at 16:43

1 Answers1

1

There's io.StringIO:

from io import StringIO

files.append(StringIO("Hello\n"))
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21