io python_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("Yes\nYEs")

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值