介绍
StringIO
- 导入 from io import StringIO
- 内存中,开辟的一个文本模式的buffer,可以像文件对象一样操作它
- 当close方法调用的时候,这个buffer会被释放
stringIO操作
class io.StringIO(initial_value=”, newline=’\n’)
The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.
初始化默认的value值可以提供初始化buffer内容,如果新行转化开启,新行会被write()覆盖,seek位置在buffer的起始位置。
getvalue
getvalue()
Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.
返回buffer容器中包含所有的字符串,新行也被当read()解码,经过seek位置已经变化
代码实现对比1:
from io import StringIO
sio = StringIO(initial_value='goodek',newline='\n')
print(sio.readable(),sio.writable(),sio.seekable())
#sio.write('magedu\nPython')
sio.seek(0)
print(sio.read())
运行结果:
True True True
goodek
代码实现对比2:
from io import StringIO
sio = StringIO(initial_value='goodek',newline='\n')
print(sio.readable(),sio.writable(),sio.seekable())
sio.write('magedu\nPython')
sio.seek(0)
print(sio.read())
运行结果:
True True True
magedu
Python
代码实现对比3
from io import StringIO
from io import BytesIO
f = StringIO('Hello!\nHi!\nGoodbye!')
print(f.getvalue())
while True:
s = f.readline()
if s == '':
break
print(s.strip())
运行结果:
Hello!
Hi!
Goodbye!
Hello!
Hi!
Goodbye!
StringIO好处
一般来说,磁盘的操作比内存的操作要慢得多,内存足够的情况下,一般的优化思路是少落地,减少磁盘IO的过程,可以大大提高程序的运行效率
BytesIO
- IO模块中的类
from io import BytesIO - 内存中,开辟的一个二进制模式的buffer,可以像文件对象一样操作它
- 当close方法被调用的时候,这个buffer会被释放
BytesIO操作
BytesIO([initial_bytes])
A stream implementation using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called.
getbuffer()
Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:
返回一个可读可写的view,view包含整个buffer内容,并非拷贝
代码实现1
from io import BytesIO
bio = BytesIO(b'abcdef')
print(bio.readable(),bio.writable(),bio.seekable())
view = bio.getbuffer()
view[2:4] = b'56'
print(bio.getvalue())
运行结果:
True True True
b'ab56ef'
代码实现2
# -*- coding: UTF-8 -*-
from io import BytesIO
bio = BytesIO(b'abcdef')
print(bio.readable(),bio.writable(),bio.seekable())
bio.write('中国'.encode('UTF-8'))
print(bio.getvalue())
f = BytesIO(b'\xe4\xb8\xad\xe5\x9b\xbd')
print(f.read())
BytesIO好处
- 一般来说,磁盘的操作比内存的操作要慢得多,内存足够的情况下,一般的优化思路是少落地,减少磁盘IO的过程,可以大大提高程序的运行效率
file-like对象
- 类文件对象、可以像文件对象一样操作
- socket对象、输入输出对象(stdin、stdout)都是类文件对象
from sys import stdout
f = stdout
print(type(f))
f.write('hello python')
运行结果:
<class '_io.TextIOWrapper'>
hello python
本文介绍了Python中StringIO和BytesIO的使用方法,包括如何初始化、读写操作及获取内容等。通过代码示例展示了如何利用这些工具提高程序效率。
297

被折叠的 条评论
为什么被折叠?



