日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python学习笔记 - StringIO以及BytesIO

發(fā)布時間:2025/4/5 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python学习笔记 - StringIO以及BytesIO 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

之前我們所說的都是讀寫真正的文件。其實我們也可以在內(nèi)存中虛擬一個文件進行讀寫。Python給咱們提供的官方module有io.StringIO和io.BytesIO.

io.StringIO

String IO用于在內(nèi)存在讀寫字符串。
StringIO可以傳入一個字符初始化。例如

string = StringIO("This is Demo")

例如:

from io import StringIOs = StringIO() s.write("Yes\nYEs") s.seek(0) # 將指針撥回到開始位置,否則將會讀取不到任何東西content = s.read() print content

StringIO創(chuàng)建的是一個file-like object,擁有File Object的所有方法。StringIO還有兩個特殊的方法,就是getvalue()方法和close()方法。

  • getvalue()方法用于獲取StringIO中寫入的內(nèi)容

  • close()方法關閉StringIO,釋放內(nèi)存。

io.BytesIO

StringIO只能處理字符串類型的數(shù)據(jù),BytesIO可以用于處理二進制類型的數(shù)據(jù)。
BytesIO的用法與StringIO類似。

StringIO.StringIO

在搜索文檔的時候,發(fā)現(xiàn)在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的遺產(chǎn),后續(xù)會被io.StringIO取代.
建議使用io.StringIO.

總結

以上是生活随笔為你收集整理的python学习笔记 - StringIO以及BytesIO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。