首页 > 编程语言 > 详细

python 在内存中读写:StringIO / BytesIO

时间:2018-07-23 18:36:19      阅读:225      评论:0      收藏:0      [点我收藏+]


操作字符串,使用StringIO

#!/usr/bin/python
# -*- coding: utf-8 -*-

from io import StringIO

f = StringIO()
f.write('hello')

print(f.getvalue())

运行结果:

Traceback (most recent call last):
  File "stringio.py", line 6, in <module>
    f.write('hello')
TypeError: unicode argument expected, got 'str'

在python 2.7版本中出错,在python 3版本中正常运行,于是百度了一下,把

from io import StringIO

改为

from io import BytesIO as StringIO


继续在python2.7版本中运行,正常了。

#!/usr/bin/python
# -*- coding: utf-8 -*-

#from io import StringIO
#from io import BytesIO
from io import BytesIO as StringIO
f = StringIO()
f.write('hello')

print(f.getvalue())

运行结果:

hello




操作二进制文件,使用BytesIO

以下代码在python2.7运行又有问题,目前时间不够,为节省时间,在python3平台运行,成功

#!/usr/bin/python
# -*- coding: utf-8 -*-

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())

运行结果:

hello
b'\xe4\xb8\xad\xe6\x96\x87'




python 在内存中读写:StringIO / BytesIO

原文:http://blog.51cto.com/13502993/2149155

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!