Python中BytesIO的使用場景,什麼時間應該使用BytesIO?

時間 2021-06-02 23:28:09

1樓:lxkaka

列舉一種場景,把資料寫入檔案再上傳到儲存服務比如阿里雲OSS, aws的S3,這個時候可以用ByetesIO來讀寫資料。

2樓:黃哥

Python 3 中字串是str型別,記憶體讀寫字串用StringIO。記憶體讀寫bytes 用BytesIO。bytes 和str 轉換用encode 和decode

In [4]: s = "黃哥"

In [5]: type(s)

Out[5]: str

In [6]: b = s.encode('utf-8')

In [7]: b

Out[7]: b'\xe9\xbb\x84\xe5\x93\xa5'

In [8]: type(b)

Out[8]: bytes

In [9]: c = b.decode('utf-8')

In [10]: c

Out[10]: '黃哥'

In [11]:

class io.StringIO(initial_value='', newline='\n')An in-memory stream for text I/O. The text buffer is discarded when the close() method is called.

The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.

StringIO provides this method in addition to those from TextIOBase and its parents:

class io.BytesIO([initial_bytes])A stream implementation using an in-memory bytes buffer. It inherits BufferedIOBase.

The buffer is discarded when the close() method is called.

The optional argument initial_bytes is a bytes-like object that contains initial data.

BytesIO provides or overrides these methods in addition to those from BufferedIOBaseand IOBase:

getbuffer()16.2. io — Core tools for working with streams

Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:

>>>>>> b = io.BytesIO(b"abcdef")

>>> view = b.getbuffer()

>>> view[2:4] = b"56"

>>> b.getvalue()

b'ab56ef'

Note

As long as the view exists, the BytesIO object cannot be resized or closed.

New in version 3.2.

python中的beautifulsoup和xpath有什麼異同點?

我覺得不同主要有以下幾點 學習曲線 效能曲線 對新手友好度 全宇宙最好的文字標籤解析庫當然是bs了,可一遇到js還是表示很無奈,非要說x系列快點實在沒有必要哈哈哈 我怎麼覺得xpath比bs好用多了。並且也很靈活。特別新版本的lxml更強大 beautifulsoup 是 HTML 解析庫,XPat...

python中enumerate object究竟是一種怎樣的存在形式呢?

l Ass We Can type of l is tuplee enumerate l type of e is enumerate objectforv inenumerate e type of enumerate e is enumerate object print v type of v...

Python中ASCII,Unicode,UTF 8,encode,decode這些有什麼關係?

NoOffense ASCII,UTF 8是常用的字元編碼型別,Unicode是字符集,它們跟具體某一門語言 比如Python 無關,是計算機通行的標準。字元編碼型別規定了位元組 bytes 和字元 character 是如何對應的。例如ASCII中,10進製65代字元 A UTF 8中,16進製制...