如何用python把任意文件转换为“1010”样子的文本

2025-01-01 05:14:02
推荐回答(1个)
回答1:

# path参数:要转换的文件的路径
def convertFileToOneAndZero(path):
f = open(path,'rb')
src = f.read()
print len(src)

result = []
for i in src:
temp = bin(ord(i))[2:]
temp = '0' * (8-len(temp)) + temp
result.append(temp)

return ''.join(result)

# src参数:1010字符串
# path参数:输出文件的路径
def convertOneAndZeroToFile(src, path):
result = []
for i in range(0, len(src), 8):
result.append(chr(int(src[i:i+8], 2)))

f = open(path, 'wb')
f.write(''.join(result))
f.close()