脚本宝典收集整理的这篇文章主要介绍了python学习笔记 - StringIO以及BytesIO,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
之前我们所说的都是读写真正的文件。其实我们也可以在内存中虚拟一个文件进行读写。Python给咱们提供的官方module有io.StringIO
和io.BytesIO
.
io.StringIO
String IO用于在内存在读写字符串。
StringIO可以传入一个字符初始化。例如
string = StringIO("This is Demo")
例如:
From io import StringIO
s = StringIO()
s.wrITe("YesnYEs")
s.seek(0)
# 将指针拨回到开始位置,否则将会读取不到任何东西
content = s.read()
PRint content
StringIO创建的是一个file-like object,拥有File Object的所有方法。StringIO还有两个特殊的方法,就是getvalue()
方法和close()
方法。
getvalue()方法用于获取StringIO中写入的内容
close()方法关闭StringIO,释放内存。
io.BytesIO
StringIO只能处理字符串类型的数据,BytesIO可以用于处理二进制类型的数据。
BytesIO的用法与StringIO类似。
StringIO.StringIO
在搜索文档的时候,发现在StringIO下也有一个StringIO,而且两者非常类似。所有GOOGLE了一下。在stackoverflow有一个回答:
回答的原文链接:http://stackoverflow.com/ques...
An in-memory stream for unicode text. It inherits TextIOWrapPEr.
This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
io.StringIO is a class. It handles Unicode. It reflects the preferred Python 3 library structure.
StringIO.StringIO is a class. It handles strings. It reflects the legacy Python 2 library structure.
What should be preferred?
Always move forward toward the new library organization. The io.open should be used to replace the built-in Unicode-unaware open.
Forward. Move forward.
大意就是StringIO是python2的遗产,后续会被io.StringIO取代.
建议使用io.StringIO.
以上是脚本宝典为你收集整理的python学习笔记 - StringIO以及BytesIO全部内容,希望文章能够帮你解决python学习笔记 - StringIO以及BytesIO所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。