首先需要将输入字符串转换为字节:def _to_Bytes(data):
b = bytearray()
for i in range(0, len(data), 8):
b.append(int(data[i:i+8], 2))
return bytes(b)
然后,打开一个文件以二进制模式写入:
^{pr2}$
现在,将原始字符串写入文件,可以进行字节比较:import os
with open('test_compare.txt', 'a') as f:
f.write('The quick brown fox jumps over the lazy dog')
_o = os.path.getsize('test_compare.txt')
_c = os.path.getsize('test.bin')
print(f'Original file: {_o} bytes')
print(f'Compressed file: {_c} bytes')
print('Compressed file to about {}% of original'.format(round((((_o-_c)/_o)*100), 0)))
输出:Original file: 43 bytes
Compressed file: 25 bytes
Compressed file to about 42.0% of original
要恢复原始状态,可以编写一个函数来确定字符的可能顺序:d = {'