python将txt文件转为字符串,Python:将文本文件转换为二进制文件

本文介绍了如何使用Python将1MB的文本文件转换为二进制字符串,并探讨了如何逆向操作,即从二进制数到文本文件的转换。标准编码库提供了解码和编码功能,如UTF-8,通过`bytes_to_string`和`string_to_bytes`函数实现转换。
摘要由CSDN通过智能技术生成

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值