1. io文本、十進制和原始流I/O工具
io模塊在解釋器的內置open()之上實作了一些類來完成基于檔案的輸入和輸出操作,這些類得到了適當的分解,從而可以針對不同的用途重新組合——例如,支持向一個網路套接字寫Unicode資料,
1.1 記憶體中的流
StringIO提供了一種很便利的方式,可以使用檔案API(如read()、write()等)處理記憶體中的文本,有些情況下,與其他一些字串連接技術相比,使用StringIO構造大字串可以提供更好的性能,記憶體中的流緩沖區對測驗也很有用,寫入磁盤上真正的檔案并不會減慢測驗套件的速度,
下面是使用StringIO緩沖區的一些標準例子,
import io # Writing to a buffer output = io.StringIO() output.write('This goes into the buffer. ') print('And so does this.', file=output) # Retrieve the value written print(output.getvalue()) output.close() # discard buffer memory # Initialize a read buffer input = io.StringIO('Inital value for read buffer') # Read from the buffer print(input.read())
這個例子使用了read(),不過也可以用readline()和readlines()方法,StringIO類還提供了一個seek()方法,讀取文本時可以在緩沖區中跳轉,如果使用一種前向決議演算法,則這個方法對于回轉很有用,

要處理原始位元組而不是Unicode文本,可以使用BytesIO,
import io # Writing to a buffer output = io.BytesIO() output.write('This goes into the buffer. '.encode('utf-8')) output.write('á?ê'.encode('utf-8')) # Retrieve the value written print(output.getvalue()) output.close() # discard buffer memory # Initialize a read buffer input = io.BytesIO(b'Inital value for read buffer') # Read from the buffer print(input.read())
寫入BytesIO實體的值一定是bytes而不是str,

1.2 為文本資料包裝位元組流
原始位元組流(如套接字)可以被包裝為一個層來處理串編碼和解碼,從而可以更容易地用于處理文本資料,TextIOWrapper類支持讀寫,write_through引數會禁用緩沖,并且立即將寫至包裝器的所有資料重繪輸出到底層緩沖區,
import io # Writing to a buffer output = io.BytesIO() wrapper = io.TextIOWrapper( output, encoding='utf-8', write_through=True, ) wrapper.write('This goes into the buffer. ') wrapper.write('á?ê') # Retrieve the value written print(output.getvalue()) output.close() # discard buffer memory # Initialize a read buffer input = io.BytesIO( b'Inital value for read buffer with unicode characters ' + 'á?ê'.encode('utf-8') ) wrapper = io.TextIOWrapper(input, encoding='utf-8') # Read from the buffer print(wrapper.read())
這個例子使用了一個BytesIO實體作為流,對應bz2、http,server和subprocess的例子展示了如何對其他型別的類似檔案的物件使用TextIOWrapper,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/168207.html
標籤:Python
