Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: create a file object from a string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading