【发布时间】:2020-03-22 23:59:13
【问题描述】:
我编写了一个代码(在帖子末尾给出),它只是将文件的字节(=byte_obj)转换为二进制数binary_dt,所以我希望byte_obj 中的位数和binary_dt 相同,但事实并非如此,我使用了一个 3 KB 的文本文件并得到了 17 KB 文件的输出(输出 = 将binary_dt写入文本文件),这是为什么呢?
注意,文件byte_obj中的byte-object的个数是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()
【问题讨论】:
标签: python python-3.x memory binaryfiles binary-data