[关闭]
@Scrazy 2016-02-15T08:41:06.000000Z 字数 1038 阅读 1099

String和ByteIO


python学习笔记


StringIO

读写数据时并不一定是文件,也可以在内存中读写。StringIO就是在内存中读写str

  1. >>> from io import StringIO
  2. >>> f = StringIO()
  3. >>> f.write('Hello World'
  4. 11
  5. >>> f.write('\nI Like Python')
  6. 14
  7. >>> print(f.getvalue())
  8. Hello World
  9. I Like Python

getvalue()方法用于获得写入后的str
我们也可以使用循环的方法来读取文件:

  1. >>> from io import StringIO
  2. >>> f = StringIO('Hello!\nWorld!\nI Like Python')
  3. >>> while True:
  4. ... s = f.readline()
  5. ... if s == '': # 读取完成则break
  6. ... break
  7. ... print(s.strip())#strip()是为了去掉转行的空行
  8. ...
  9. Hello!
  10. World!
  11. I Like Python

下面是print(s)的输出结果(区别于print(s.strip())

  1. >>> from io import StringIO
  2. >>> f = StringIO('Hello\nI\nLike\nPython')
  3. >>> while True:
  4. ... s = f.readline()
  5. ... if s == '':
  6. ... break
  7. ... print(s)
  8. ...
  9. Hello
  10. I
  11. Like
  12. Python

BytesIO

StringIO操作只能是str,对于二进制数据的操作就需要使用BytesIO

  1. >>> from io import BytesIO
  2. >>> f = BytesIO()
  3. >>> f.write('中文'.encode('utf-8'))
  4. 6
  5. >>> print(f.getvalue())
  6. b'\xe4\xb8\xad\xe6\x96\x87'

写入的数据是经过UTF-8编码过的bytes不是str
StringIO类似,也可以用一个bytes初始化一个BytesIO然后像读取文件一样读取:

  1. >>> from io import StringIO
  2. >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87\xff\xfe-N\x87e')#这是`utf-16`的‘中文’('中文'.encode('utf-16'))
  3. >>> f.read()
  4. b'\xe4\xb8\xad\xe6\x96\x87\xff\xfe-N\x87e'

参考来源

廖雪峰的网站

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注