且构网

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

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

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

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

>>>从 cStringIO 导入 StringIO>>>f = StringIO('foo')>>>f.read()'富'

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

对于 Python 3.x,使用 io代码> 模块.

f = io.StringIO('foo')

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

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