Dar*_*zer 107
对于Python 2.x,请使用StringIO模块.例如:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
Run Code Online (Sandbox Code Playgroud)
我使用cStringIO(更快),但请注意它不接受无法编码为纯ASCII字符串的Unicode字符串.(您可以通过将"从cStringIO"更改为"from StringIO"来切换到StringIO.)
对于Python 3.x,请使用该io
模块.
f = io.StringIO('foo')
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 25
在Python 3.0中:
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您的类文件对象预期包含字节,则应首先将字符串编码为字节,然后可以使用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')))
Run Code Online (Sandbox Code Playgroud)