Convert bytes to a string

后端 未结 19 2250
野性不改
野性不改 2020-11-21 04:45

I\'m using this code to get standard output from an external program:

>>> from subprocess import *
>>> command_stdout = Popen([\'ls\', \'-l         


        
19条回答
  •  野的像风
    2020-11-21 05:00

    When working with data from Windows systems (with \r\n line endings), my answer is

    String = Bytes.decode("utf-8").replace("\r\n", "\n")
    

    Why? Try this with a multiline Input.txt:

    Bytes = open("Input.txt", "rb").read()
    String = Bytes.decode("utf-8")
    open("Output.txt", "w").write(String)
    

    All your line endings will be doubled (to \r\r\n), leading to extra empty lines. Python's text-read functions usually normalize line endings so that strings use only \n. If you receive binary data from a Windows system, Python does not have a chance to do that. Thus,

    Bytes = open("Input.txt", "rb").read()
    String = Bytes.decode("utf-8").replace("\r\n", "\n")
    open("Output.txt", "w").write(String)
    

    will replicate your original file.

提交回复
热议问题