如何在 Python 中将字符串包装在文件中? [英] How do I wrap a string in a file in Python?

查看:38
本文介绍了如何在 Python 中将字符串包装在文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用字符串的内容创建类文件对象(与 File 相同的鸭子类型)?

解决方案

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

这篇关于如何在 Python 中将字符串包装在文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆