天天看點

python檔案操作StringIO和BytesIOStringIO操作

StringIO操作

io子產品中的類

導入:from io import StringIO

記憶體中開辟的一個文本模式的buffer,可以像檔案對象一樣操作,當close方法被調用的時候,這個buffer會被釋放

  • getvalue()  擷取全部内容,與檔案指針無關
from io import StringIO

# 記憶體中建構
sio = StringIO()  # 像檔案對象一樣操作
print(sio.readable(), sio.writable(), sio.seekable())
sio.write("hello\npython")
sio.seek(0)
print(1, sio.readline())
print(2, sio.read())
sio.seek(0)
print(3, sio.readlines())
print(4, sio.getvalue())          # 無視指針,輸出全部内容
sio.close()      

運作結果

True True True
1 hello

2 python
3 ['hello\n', 'python']
4 hello
python      

使用上下文管理

with StringIO() as sio:
    sio.write('abcd')
    sio.seek(0)
    print(sio.read())      

運作結果

abcd      

使用StringIO的好處:

  一般來說,磁盤的操作比記憶體操作要慢很多,記憶體充足的情況下,優化的思路是少落地,減少磁盤IO的過程,可以大大提高程式運作效率

BytesIO

io子產品中的類

導入:from io import BytesIO

記憶體中開辟的一個二進制模式的buffer,可以像檔案對象一樣操作,當close方法被調用的時候,這個buffer會被釋放

from io import BytesIO
bio=BytesIO()
print(bio.readable(), bio.writable(), bio.seekable())
bio.write(b'hello\npython')
bio.seek(0)
print(1, bio.readline())
print(2, bio.getvalue())  # 無視指針,輸出全部内容
bio.close()      

運作結果

True True True
1 b'hello\n'
2 b'hello\npython'      

file-like對象

類檔案對象,可以向檔案對象一樣操作

socket對象、輸入輸出對象(stdin、stdout)都是類檔案對象

from sys import stdout

f = stdout
print(type(f))
print(f.readable(), f.writable(), f.seekable())
f.write('abc')
           

運作結果

<class '_io.TextIOWrapper'>
False True True
abc
           

 print方法就是向标準輸出列印内容,就相當于在write内容到stdout

繼續閱讀