python中eval,python中StringIO和BytesIO

 2023-11-05 阅读 28 评论 0

摘要:StringIO 很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。 StringIO顧名思義就是在內存中讀寫str。 要把str寫入StringIO,我們需要先創建一個StringIO,然后,像文件一樣寫入即可: >>> from io import StringIO >&g

StringIO

很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。

StringIO顧名思義就是在內存中讀寫str。

要把str寫入StringIO,我們需要先創建一個StringIO,然后,像文件一樣寫入即可:

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello') 5 >>> f.write(' ') 1 >>> f.write('world!') 6 >>> print(f.getvalue()) hello world! 

getvalue()方法用于獲得寫入后的str。

python中eval?要讀取StringIO,可以用一個str初始化StringIO,然后,像讀文件一樣讀取:

>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!') >>> while True: ... s = f.readline() ... if s == '': ... break ... print(s.strip()) ... Hello! Hi! Goodbye! 

BytesIO

StringIO操作的只能是str,如果要操作二進制數據,就需要使用BytesIO。

BytesIO實現了在內存中讀寫bytes,我們創建一個BytesIO,然后寫入一些bytes:

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8')) 6 >>> print(f.getvalue()) b'\xe4\xb8\xad\xe6\x96\x87' 

請注意,寫入的不是str,而是經過UTF-8編碼的bytes。

和StringIO類似,可以用一個bytes初始化BytesIO,然后,像讀文件一樣讀取:

>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') >>> f.read() b'\xe4\xb8\xad\xe6\x96\x87' 

小結

python str轉byte?StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。

轉載于:https://www.cnblogs.com/fengff/p/9007010.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/166611.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息