python中IO库中StringIO方法和BytesIO方法用法详解
有时候数据读写不一定是文件,也可以在内存中读写。StringIO顾名思义就是在内存中读写str。
Python在内存中读写数据,用到的模块是StringIO和BytesIO。
getvalue()方法用于获得写入后的str。
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
StringIO用法:
源码解释: class StringIO(_TextIOBase): """ Text I/O implementation using an in-memory buffer. The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrappers constructor. """
示例代码1:
# StringIO:在内存中读写str from io import StringIO f = StringIO() print(f.write(hello)) print(f.write( )) print(f.write(world!)) # getValue()方法用于获取写入的str print(f.getvalue()) print(-----------------------1) # 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取: f = StringIO(Hello! Hi! Goodbye!) while True: s = f.readline() if s == : break print(s.strip()) print(-----------------------2)
运行结果:
BytesIO用法:
# 源码解释: class BytesIO(_BufferedIOBase): """ Buffered I/O implementation using an in-memory bytes buffer. """
示例代码2:
# StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO from io import BytesIO f = BytesIO() print(f.write(中国 我爱你.encode(utf-8))) print(f.getvalue()) print(-----------------------1) # 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取 f = BytesIO(bxe4xb8xadxe5x9bxbd xe6x88x91xe7x88xb1xe4xbdxa0) print(f.read()) while True: s = f.readline() if s == b: break print(s.strip()) print(-----------------------2)
运行结果: