如何使用字符串的内容创建类似文件的对象(与文件相同的鸭子类型)?
答案 0 :(得分:97)
对于Python 2.x,请使用StringIO模块。例如:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
我使用cStringIO(更快),但请注意它不是accept Unicode strings that cannot be encoded as plain ASCII strings。 (您可以通过将“从cStringIO”更改为“from StringIO”来切换到StringIO。)
对于Python 3.x,请使用io
模块。
f = io.StringIO('foo')
答案 1 :(得分:24)
在Python 3.0中:
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
答案 2 :(得分:5)
如果类文件对象应包含字节,则应首先将字符串编码为字节,然后可以使用BytesIO对象。在Python 3中:
from io import BytesIO
string_repr_of_file = 'header\n byline\n body\n body\n end'
function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
答案 3 :(得分:3)
两个好的答案。我想添加一个小技巧 - 如果你需要一个真正的文件对象(有些方法需要一个,而不仅仅是一个接口),这里有一种创建适配器的方法:
答案 4 :(得分:2)
这适用于Python2.7和Python3.x:
io.StringIO(u'foo')