python : StringIO 和 BytesIO:
--數據讀寫不一定是文件,也可以在內存中讀寫
StringIO:
顧名思義就是在內存中讀寫str。
from io import StringIO
f= StringIO()
f.write('') # 寫入
---》f.getvalue() #獲取寫入的數據(str)
--StringIO操作的只能是str!!
--讀取StringIO,用一個str初始化StringIO,像讀文件一樣讀取
BytesIO:
要操作二進制數據,就需要使用BytesIO。
BytesIO實現了在內存中讀寫bytes
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
#讀取數據
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read() # 只能讀一次,再讀為空。 可以把f.read()賦給某個變量,然后解碼變量,顯示值
#樣式一:
>>> from io import StringIO # 導入StringIO類
>>> f = StringIO() # 創建一個實例,賦給f對象
>>> f.write('hello') # 往 f 中寫入
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue()) #getvalue()方法用於獲得寫入后的str
hello world!
#樣式二:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!') #創建一個帶內容的實例
>>> while True: # while循環
... s = f.readline() # 按行讀取內容
... if s == '':
... break
... print(s.strip()) # strip(),刪除行首行尾的空格
總結:
StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。