我已经写了一个代码(在文章末尾给出),该代码将文件的字节(= byte_obj
)简单地转换为二进制数binary_dt
,所以我希望byte_obj
中的位数和binary_dt
是相同的,但事实并非如此,我使用了一个3 KB的文本文件,并获得了17 KB文件的输出(输出=将binary_dt
写入文本文件),为什么呢?
注意,文件的byte_obj
中的字节对象数为2117,byte_obj
的大小(由于结构数据,实际内容有开销)为2150,因此此处的差别不大..
所以,谁能解释什么问题?如果我想从binary_dt
和byte_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: