RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
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, in 
    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://sczitong.cn/article/jpeioh.html