首页 > 文章列表 > python中StringIO的读写

python中StringIO的读写

Python StringIO
326 2022-08-07

1、概念

StringIO是在内存中读写str。

为了将str写到StringIO中,首先需要创建StringIO,然后像文件一样写它:

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!

2、为了读取StringIO,可以初始化带有一个str的StringIO,然后像读取文件一样读取:

>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
...     s = f.readline()
...     if s == '':
...         break
...     print(s.strip())
...
Hello!
Hi!
Goodbye!

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。