How to transfer a string to a file in Python?

How to create a file-like object (the same type of duck as the File), with the contents of the line?

+59
python string file stringio
Sep 26 '08 at 19:33
source share
3 answers

For Python 2.x, use the StringIO module. For example:

>>> from cStringIO import StringIO >>> f = StringIO('foo') >>> f.read() 'foo' 

I use cStringIO (this is faster), but note that it does not 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') 
+77
Sep 26 '08 at 19:34
source share

In Python 3.0:

 import io with io.StringIO() as f: f.write('abcdef') print('gh', file=f) f.seek(0) print(f.read()) 
+19
Sep 26 '08 at 10:00
source share

Two good answers. Id add a little trick - if you need a real file object (some methods expect it, not just an interface), here is a way to create an adapter:

+1
Sep 27 '08 at 12:19
source share



All Articles