python学习笔记 - StringIO以及BytesIO
之前我們所說的都是讀寫真正的文件。其實(shí)我們也可以在內(nèi)存中虛擬一個(gè)文件進(jìn)行讀寫。Python給咱們提供的官方module有io.StringIO和io.BytesIO.
io.StringIO
String IO用于在內(nèi)存在讀寫字符串。
StringIO可以傳入一個(gè)字符初始化。例如
例如:
from io import StringIOs = StringIO() s.write("Yes\nYEs") s.seek(0) # 將指針撥回到開始位置,否則將會讀取不到任何東西content = s.read() print contentStringIO創(chuàng)建的是一個(gè)file-like object,擁有File Object的所有方法。StringIO還有兩個(gè)特殊的方法,就是getvalue()方法和close()方法。
getvalue()方法用于獲取StringIO中寫入的內(nèi)容
close()方法關(guān)閉StringIO,釋放內(nèi)存。
io.BytesIO
StringIO只能處理字符串類型的數(shù)據(jù),BytesIO可以用于處理二進(jìn)制類型的數(shù)據(jù)。
BytesIO的用法與StringIO類似。
StringIO.StringIO
在搜索文檔的時(shí)候,發(fā)現(xiàn)在StringIO下也有一個(gè)StringIO,而且兩者非常類似。所有g(shù)oogle了一下。在stackoverflow有一個(gè)回答:
回答的原文鏈接: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的遺產(chǎn),后續(xù)會被io.StringIO取代.
建議使用io.StringIO.
總結(jié)
以上是生活随笔為你收集整理的python学习笔记 - StringIO以及BytesIO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET url 的编码与解码
- 下一篇: opencv3——ANN算法的使用