>>> from io import StringIO >>> # 內存中構建 >>> sio = StringIO() # 像文件對象同樣操做 >>> print(sio, sio.readable(), sio.writable(), sio.seekable()) <_io.StringIO object at 0x0000010B14ECE4C8> True True True >>> sio.write("hello,world!") 12 >>> sio.seek(0) 0 >>> sio.readline() 'hello,world!' >>> sio.getvalue() # 無視指針,輸出所有內容 'hello,world!' >>> sio.close()
>>> from io import BytesIO >>> # 內存中構建 >>> bio = BytesIO() >>> print(bio, bio.readable(), bio.writable(), bio.seekable()) <_io.BytesIO object at 0x0000010B14ED7EB8> True True True >>> bio.write(b"hello,world!) 12 >>> bio.seek(0) 0 >>> bio.readline() b'hello,world!' >>> bio.getvalue() # 無視指針,輸出所有內容 b'hello,world!' >>> bio.close()
>>> from sys import stdout >>> f = stdout >>> print(type(f)) <class 'ipykernel.iostream.OutStream'> >>> f.write("hello,world!") hello,world!