Python: Converting a Text File to a Binary File

2020-04-30 02:33发布

We can convert any digital file into binary file.

I have a text file of 1MB,

I want to convert it to a binary string and see the output as a binary number and the vice versa,

in other words, if I have binary number, I want to convert it to a text file.

How could I do that in Python? is there a standard way to do this?

Now in this forum there are some posts (1,2,3, 4 ) on this but none of them answer properly to my question.

1条回答
仙女界的扛把子
2楼-- · 2020-04-30 03:10

See https://docs.python.org/3/library/codecs.html#standard-encodings for a list of standard string encodings, because the conversion depends on the encoding.

These functions will help to convert between bytes/ints and strings, defaulting to UTF-8.

The example provided uses the Hangul character "한" in UTF-8.


def bytes_to_string(byte_or_int_value, encoding='utf-8') -> str:
    if isinstance(byte_or_int_value, bytes):
        return byte_or_int_value.decode(encoding)
    if isinstance(byte_or_int_value, int):
        return chr(byte_or_int_value).encode(encoding).decode(encoding)
    else: 
        raise ValueError('Error: Input must be a bytes or int type')

def string_to_bytes(string_value, encoding='utf-8') -> bytes:
    if isinstance(string_value, str):
        return bytes(string_value.encode(encoding))
    else: 
        raise ValueError('Error: Input must be a string type')

int_value = 54620
bytes_value = b'\xED\x95\x9C'
string_value = '한'

assert bytes_to_string(int_value) == string_value
assert bytes_to_string(bytes_value) == string_value
assert string_to_bytes(string_value) == bytes_value
查看更多
登录 后发表回答