为什么文件中的位数和同一文件的二进制表示不同?

Why the Number of Bits is Different in File and The Binary Representation of the same File?

我写了一个代码(在post末尾给出),它只是简单地将一个文件的字节(=byte_obj)转换成一个二进制数binary_dt,所以我希望 byte_objbinary_dt 中的位数相同,但事实并非如此,我使用了一个 3 KB 的文本文件并得到了 17 KB 文件的输出(输出 = 写入 binary_dt到文本文件),这是为什么?

注意,文件byte_obj中byte-object的个数是2117,byte_obj的大小(由于结构数据,在实际内容上有开销)是2150,这里差别不大..

那么,有什么问题可以解释一下吗?如果我想从 binary_dtbyte_obj 中获得相同数量的位数,我该怎么办?

import sys

input_file="a.txt";output_file="b.txt"
with open(input_file, "rb") as file: #--> open file in binary read mode
  byte_obj = file.read() #--> read all binary data


print("Number of byte-object in 'byte_obj' = ",len(byte_obj))
print("The size of 'byte_obj' (has an overhead over the actual content, due to structure data) = \n",str(sys.getsizeof( byte_obj))) #Return the size of an object in bytes.


binary_dt=bin(int.from_bytes( byte_obj, byteorder=sys.byteorder))

print("The number of bits in 'binary_dt' on PC= \n",len(binary_dt)) #Return the size of an object in bytes.
print("binary_dt: \n",binary_dt)

text_file = open(output_file, "w")
n = text_file.write(binary_dt)
text_file.close()

这是因为您正在读取二进制文件并写入 ASCII:

>>> bin(3)
'0b11'

这里是2位转换成4字节。