之前我们所说的都是读写真正的文件。其实我们也可以在内存中虚拟一个文件进行读写。python给咱们提供的官方module有io.stringio和io.bytesio.
io.StringIO
String IO用于在内存在读写字符串。StringIO可以传入一个字符初始化。例如
string = StringIO("This is Demo")
登录后复制
例如:
from io import StringIOs = StringIO()s.write("YesYEs")s.seek(0)# 将指针拨回到开始位置,否则将会读取不到任何东西content = s.read()print content
登录后复制
StringIO创建的是一个file-like object,拥有File Object的所有方法。StringIO还有两个特殊的方法,就是getvalue()方法和close()方法。
立即学习“Python免费学习笔记(深入)”;
getvalue()方法用于获取StringIO中写入的内容
close()方法关闭StringIO,释放内存。
io.BytesIO
StringIO只能处理字符串类型的数据,BytesIO可以用于处理二进制类型的数据。BytesIO的用法与StringIO类似
StringIO.StringIO
在搜索文档的时候,发现在StringIO下也有一个StringIO,而且两者非常类似。所有google了一下。在stackoverflow有一个回答:
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相关文章请关注PHP中文网!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2279507.html