Python get rid of bytes b' '

后端 未结 6 1440
悲&欢浪女
悲&欢浪女 2021-02-18 17:24
import save

string = \"\"

with open(\"image.jpg\", \"rb\") as f:
    byte = f.read(1)
    while byte != b\"\":
        byte = f.read(1)
        print ((byte))
<         


        
6条回答
  •  别那么骄傲
    2021-02-18 17:50

    The b'', is only the string representation of the data that is written when you print it.

    Using decode will not help you here because you only want the bytes, not the characters they represent. Slicing the string representation will help even less because then you are still left with a string of several useless characters ('\', 'x', and so on), not the original bytes.

    There is no need to modify the string representation of the data, because the data is still there. Just use it instead of the string (i.e. don't use print). If you want to copy the data, you can simply do:

    data = file1.read(...)
    ...
    file2.write(data)
    

    If you want to output the binary data directly from your program, use the sys.stdout.buffer:

    import sys
    
    sys.stdout.buffer.write(data)
    

提交回复
热议问题