本文實例講述了Python內存讀寫操作。分享給大家供大家參考,具體如下:
Python中的讀寫不一定只是文件,還有可能是內存,所以下面實在內存中的讀寫操作
示例1:
# -*- coding:utf-8 -*-#! python3from io import StringIOf=StringIO()f.write('everything')f.write('is')f.write('possible')print(f.getvalue())
運行結果:
everythingispossible
在內存中新建一個StringIO
,然后進行寫入
獲取的時候用的是getvalue()
函數
而讀取的時候可以用一個循環判斷,比如:
示例2:
# -*- coding:utf-8 -*-#! python3f=StringIO('everything is possible')while True: s=f.readline() if s=='': break print(s.strip())
運行結果:
everything is possible
同理,可以操作不只是str,還可以是二進制數據,所以會用到BytesIO
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()b'/xe4/xb8/xad/xe6/x96/x87'
注:這里的測試環境為Python3,如果使用Python2運行上述示例1的話會提示如下錯誤:
Traceback (most recent call last):
File "C:/py/jb51PyDemo/src/Demo/strIODemo.py", line 5, in <module>
f.write('everything')
TypeError: unicode argument expected, got 'str'
解決方法為將
from io import StringIO
更換成:
from io import BytesIO as StringIO
即可運行得到正常結果!
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答