美文网首页
StringIO和BytesIO

StringIO和BytesIO

作者: 噜噜迅儿 | 来源:发表于2018-05-26 22:23 被阅读0次

    StringIO

    StringIO操作的只能是str!!

    ## str写入StringIO
    from io import StringIO
    f = StringIO()
    f.write('hello')
    f.write(' ')
    f.write('world!')
    f.getvalue()
    
    ## 读取StringIO
    from io import StringIO
    f = StringIO('Hello!\nHi!\nGoodbye!')
    while True:
        s = f.readline()
        if s == '':
            break
        print(s.strip())
    

    BytesIO

    ## 二进制数据写入BytesIO
    from io import BytesIO
    f = BytesIO()
    f.write('中文'.encode('utf-8'))
    f.getvalue()
    
    ## 读取BytesIO
    from io import BytesIO
    f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
    f.read().decode('utf-8')
    

    相关文章

      网友评论

          本文标题:StringIO和BytesIO

          本文链接:https://www.haomeiwen.com/subject/spdvjftx.html