-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 ?

3
  • What was wrong with using an io.TextIOWrapper? Commented May 20, 2022 at 16:30
  • @mkrieger1: >>> import io >>> f = io.TextIOWrapper("Hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'readable' Commented May 20, 2022 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. Commented May 20, 2022 at 16:43

1 Answer 1

1

There's io.StringIO:

from io import StringIO

files.append(StringIO("Hello\n"))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.