How do I create a file-like object (same duck type as File) with the contents of a string?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
For Python 2.x, use the StringIO module. For example:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
I use cStringIO (which is faster), but note that it doesn’t accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing “from cStringIO” to “from StringIO”.)
For Python 3.x, use the io module.
f = io.StringIO('foo')
Method 2
In Python 3.0:
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
The output is:
'abcdefgh'
Method 3
This works for Python2.7 and Python3.x:
io.StringIO(u'foo')
Method 4
If your file-like object is expected to contain bytes, the string should first be encoded as bytes, and then a BytesIO object can be used instead. In Python 3:
from io import BytesIO string_repr_of_file = 'headern bylinen bodyn bodyn end' function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0