天天看點

python子產品—StringIO and BytesIO

1.StringIO子產品

在平時開發過程中,有些時候我們可能不需要寫在檔案中,我們可以直接通過StringIO子產品直接寫入到系統記憶體中,如果不用了,可以直接清除就可以了。StringIO主要是用來在記憶體中寫入字元串的,及字元串的緩存。

1.1通過StringIO寫入記憶體

例子

#from io import StringIO

from io import BytesIO as StringIO

output = StringIO()

output.write("hello,world")

print(output.getvalue())

output.truncate(0)

結果:

hello,world

說明:

Output.write()         # 寫入一個字元串

Output.getvalue()       # 使用者擷取寫入後的字元串

Output.truncate(0)      # 參數為0,表示清空所有寫入的内容

1.2通過字元串初始化一個StringIO

要讀取StringIO,可以用一個str初始化StringIO,然後,像讀檔案一樣讀取

output = StringIO("hello\nworld\nhello\nChina")

print(output.read())

while 1:

   s = output.readline()

   if s == "":

       break

   print s.strip()

hello

world

China

2.BytesIO子產品

StringIO操作的隻能是str,如果要操作二進制資料,就需要使用BytesIO;BytesIO實作了在記憶體中讀寫bytes,我們建立一個BytesIO,然後寫入一些bytes

from io import StringIO,BytesIO

f = BytesIO()

f.write(b"hello")

f.write(b"\n")

f.write("world")

print(f.getvalue())

g = BytesIO("hello\nworld")

print(g.getvalue())

本文轉自 huangzp168 51CTO部落格,原文連結:http://blog.51cto.com/huangzp/1980415,如需轉載請自行聯系原作者