Python:将文本文件转换为二进制文件 [英] Python: Converting a Text File to a Binary File
问题描述
我们可以将任何数字文件转换为二进制文件.
We can convert any digital file into binary file.
我有一个1MB的文本文件,
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,
换句话说,如果我有二进制数,我想将其转换为文本文件.
如何在Python中做到这一点?有没有标准的方法可以做到这一点?
How could I do that in Python? is there a standard way to do this?
该论坛现在有一些帖子( 1, 2 4 ),但没有一个人能正确回答我的问题.
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.
这些功能将有助于在字节/整数和字符串之间进行转换,默认为UTF-8.
These functions will help to convert between bytes/ints and strings, defaulting to UTF-8.
提供的示例在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
这篇关于Python:将文本文件转换为二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!