How do I wrap a string in a file in Python?

六眼飞鱼酱① 提交于 2019-11-26 15:57:14

问题


How do I create a file-like object (same duck type as File) with the contents of a string?


回答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')



回答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())



回答3:


Two good answers. I’d add a little trick — if you need a real file object (some methods expect one, not just an interface), here is a way to create an adapter:

  • http://www.rfk.id.au/software/filelike/



回答4:


This works for Python2.7 and Python3.x:

io.StringIO(u'foo')


来源:https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!