天天看点

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

继续阅读