操作字符串,使用StringIO
#!/usr/bin/python# -*- coding: utf-8 -*-from io import StringIOf = 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 BytesIOfrom io import BytesIO as StringIOf = StringIO()f.write('hello')print(f.getvalue())
运行结果:
hello
操作二进制文件,使用BytesIO
以下代码在python2.7运行又有问题,目前时间不够,为节省时间,在python3平台运行,成功
#!/usr/bin/python# -*- coding: utf-8 -*-from io import BytesIOf = BytesIO()f.write('中文'.encode('utf-8'))print(f.getvalue())
运行结果:
hellob'\xe4\xb8\xad\xe6\x96\x87'