您现在的位置是:课程教程文章

python中StringIO的读写

2023-12-14 22:05课程教程文章 人已围观

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!

以上就是python中StringIO的读写,希望对大家有所帮助。更多Python学习推荐:python教学

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

课程教程:python中StringIO的读写

上一篇:python BytesIO操作二进制数据

下一篇:没有了

站点信息

  • 文章统计篇文章