1. 程式人生 > >python 在內存中讀寫:StringIO / BytesIO

python 在內存中讀寫:StringIO / BytesIO

max-width int overflow .py expect code word-wrap over enc



操作字符串,使用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