Wrap an open stream with io.TextIOWrapper

后端 未结 6 1672
太阳男子
太阳男子 2020-12-05 13:16

How can I wrap an open binary stream – a Python 2 file, a Python 3 io.BufferedReader, an io.BytesIO – in an io.TextIOWrapper

6条回答
  •  暖寄归人
    2020-12-05 13:59

    It turns out you just need to wrap your io.BytesIO in io.BufferedReader which exists on both Python 2 and Python 3.

    import io
    
    reader = io.BufferedReader(io.BytesIO("Lorem ipsum".encode("utf-8")))
    wrapper = io.TextIOWrapper(reader)
    wrapper.read()  # returns Lorem ipsum
    

    This answer originally suggested using os.pipe, but the read-side of the pipe would have to be wrapped in io.BufferedReader on Python 2 anyway to work, so this solution is simpler and avoids allocating a pipe.

提交回复
热议问题