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

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

问题描述

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

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

推荐答案

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

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

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