1.StringIO的使用
# 相似文件的緩衝區
from io import StringIO
cache_file = StringIO()
print(cache_file.write('hello world')) # 11
print(cache_file.seek(0)) # 0
print(cache_file.read()) # hello world
print(cache_file.close()) # 釋放緩衝區
- StringIO常常被用來做字符串的緩存,由於StringIO的一些接口和文件操做是一致的,也就是說一樣的代碼,能夠同時當成文件操做或者StringIO操做;
- 要讀取StringIO,能夠用一個str初始化StringIO,而後像讀文件同樣讀取;
- 當使用read()方法讀取寫入的內容時,則須要先用seek()方法讓指針移動到最開始的位置,不然讀取不到內容(寫入後指針在最末尾);
- getvalue()方法:直接得到寫入後的str;
- close()方法:在關閉文件的緩衝區以後就不能再進行讀寫操做了;
2.BytesIO的使用
# 相似文件的緩衝區
from io import BytesIO
bytes_file = BytesIO()
bytes_file.write(b'hello world')
bytes_file.seek(0)
print(bytes_file.read()) # b'hello world'
bytes_file.close()
- StringIO操做的只能是str,若是要操做二進制數據,就須要使用BytesIO;
- BytesIO實現了在內存中讀寫bytes,寫入的不是str,而是通過UTF-8編碼的bytes;
- 要讀取BytesIO,能夠用一個bytes初始化BytesIO,而後像讀文件同樣讀取;