python 在内存中读写:StringIO / BytesIO
操作字符串,使用StringIO
#!/usr/bin/python#-*-coding:utf-8-*-fromioimportStringIOf=StringIO()f.write('hello')print(f.getvalue())
运行结果:
Traceback(mostrecentcalllast):File"stringio.py",line6,in<module>f.write('hello')TypeError:unicodeargumentexpected,got'str'
在python 2.7版本中出错,在python 3版本中正常运行,于是百度了一下,把
fromioimportStringIO
改为
fromioimportBytesIOasStringIO
继续在python2.7版本中运行,正常了。
#!/usr/bin/python#-*-coding:utf-8-*-#fromioimportStringIO#fromioimportBytesIOfromioimportBytesIOasStringIOf=StringIO()f.write('hello')print(f.getvalue())
运行结果:
hello
操作二进制文件,使用BytesIO
以下代码在python2.7运行又有问题,目前时间不够,为节省时间,在python3平台运行,成功
#!/usr/bin/python#-*-coding:utf-8-*-fromioimportBytesIOf=BytesIO()f.write('中文'.encode('utf-8'))print(f.getvalue())
运行结果:
hellob'\xe4\xb8\xad\xe6\x96\x87'
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。