Python3 io文本及原始流I/O工具用法詳解
io模塊在解釋器的內(nèi)置open()之上實現(xiàn)了一些類來完成基于文件的輸入和輸出操作。這些類得到了適當?shù)姆纸猓瑥亩梢葬槍Σ煌挠猛局匦陆M合——例如,支持向一個網(wǎng)絡套接字寫Unicode數(shù)據(jù)。
1.1 內(nèi)存中的流
StringIO提供了一種很便利的方式,可以使用文件API(如read()、write()等)處理內(nèi)存中的文本。有些情況下,與其他一些字符串連接技術相比,使用StringIO構造大字符串可以提供更好的性能。內(nèi)存中的流緩沖區(qū)對測試也很有用,寫入磁盤上真正的文件并不會減慢測試套件的速度。
下面是使用StringIO緩沖區(qū)的一些標準例子。
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()方法,讀取文本時可以在緩沖區(qū)中跳轉,如果使用一種前向解析算法,則這個方法對于回轉很有用。
要處理原始字節(jié)而不是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 為文本數(shù)據(jù)包裝字節(jié)流
原始字節(jié)流(如套接字)可以被包裝為一個層來處理串編碼和解碼,從而可以更容易地用于處理文本數(shù)據(jù)。TextIOWrapper類支持讀寫。write_through參數(shù)會禁用緩沖,并且立即將寫至包裝器的所有數(shù)據(jù)刷新輸出到底層緩沖區(qū)。
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。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)監(jiān)控Nginx配置文件的不同并發(fā)送郵件報警功能示例
這篇文章主要介紹了Python實現(xiàn)監(jiān)控Nginx配置文件的不同并發(fā)送郵件報警功能,涉及Python基于difflib模塊的文件比較及smtplib模塊的郵件發(fā)送相關操作技巧,需要的朋友可以參考下2019-02-02Python使用BeautifulSoup庫解析HTML基本使用教程
這篇文章主要介紹了Python使用BeautifulSoup庫解析HTML基本使用教程,文中主要對其適合于制作爬蟲方面的特性進行了解析,需要的朋友可以參考下2016-03-03