且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中将字符串包装在文件中?

更新时间:2023-01-16 11:03:33

对于Python 2.x,请使用 StringIO 模块.例如:

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

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

我使用cStringIO(速度更快),但请注意,它没有接受Unicode不能编码为纯ASCII字符串的字符串. (您可以通过将"from cStringIO"更改为"from StringIO"来切换到StringIO.)

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".)

对于Python 3.x,请使用 io 模块.

For Python 3.x, use the io module.

f = io.StringIO('foo')