一、二进制文件转文本文件
1.读取二进制文件
src_path = 'test.bin'
src_file = open(src_path, 'rb')
rb为以二进制方式读取。单独r或者w的话读写文件都是以str形式的,而rb或wb都是以byte形式写入读出。
2.创建txt文件
des_path = 'test.txt'
des_file = open(des_path,'w')
3.bin转txt
width = 4 #每次读4bytes
file_size = os.path.getsize(src_path)
i = int(file_size / width)
j = file_size % width
if j == 0:
k = 0
else:
k = 1
total_length = i + k
for i in range(total_length):
data = src_file.read(4)
dat = data[::-1] #大小端转换
res = ''.join(['%02X' %b for b in data])
des_file.write(res)
des_file.write('\n')
src_file.close()
des_file.close()
二、运行
import os
width = 4 #每次读4bytes
src_path = 'test.bin'
des_path = 'test.txt'
bin2txt(src_path, des_path, width)
src_file = open(src_path, 'rb')
des_file = open(des_path,'w')
file_size = os.path.getsize(src_path)
i = int(file_size / width)
j = file_size % width
if j == 0:
k = 0
else:
k = 1
total_length = i + k
for i in range(total_length):
data = src_file.read(4)
dat = data[::-1] #大小端转换
res = ''.join(['%02X' %b for b in dat])
des_file.write(res)
des_file.write('\n')
src_file.close()
des_file.close()