Python标准库中的io

Python标准库中io模块中有两个比较重要的组成部分:StringIO、BytesI

1.StringIO

StringIO 的作用是在内存中读写字符串,其示例代码如下:

from io import StringIO

def demo():
    # 1.创建一个StringIO
    f=StringIO()
    # 2.向内存中写入字符串 
    f.write('hello')
    f.write(' ')
    f.write('world!')
    # 3.从内存中取值
    new_str=f.getvalue()
    print(new_str)

demo()

执行上述代码,其输出结果为:

hello world!

逐行读取StringIO中的字符串的示例代码:

from io import StringIO

def demo():
    # 1.使用字符串初始化一个StringIO对象
    str_io = StringIO('Hello!\nHi!\nGoodbye!')
    while True:
        # 2.逐行读取StringIO中的字符串
        s = str_io.readline()
        if s == '

猜你喜欢

转载自blog.csdn.net/y_bccl27/article/details/121498104