python学习笔记 - StringIO以及BytesIO
之前我們所說的都是讀寫真正的文件。其實我們也可以在內存中虛擬一個文件進行讀寫。Python給咱們提供的官方module有io.StringIO和io.BytesIO.
io.StringIO
String IO用于在內存在讀寫字符串。
StringIO可以傳入一個字符初始化。例如
例如:
from io import StringIOs = StringIO() s.write("Yes\nYEs") s.seek(0) # 將指針撥回到開始位置,否則將會讀取不到任何東西content = s.read() print contentStringIO創建的是一個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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET url 的编码与解码
- 下一篇: Python数据分析学习笔记之Panda