python在内存中读写:StringIO/BytesIO
操作字符串,使用StringIO

创新互联建站是一家专注于网站建设、网站设计与策划设计,鹤城网站建设哪家好?创新互联建站做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:鹤城等地区。鹤城做网站价格咨询:18980820575
#!/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, inf.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://www.scyingshan.cn/article/jpeioh.html


咨询
建站咨询
