python读取⼆进制⽂件,转成⼗六进制格式需求:
1. 读取⼆进制(bytes)的⽂件
2. 转换为⼗六进制(hex),保存到txt纯⽂本⽂件⾥
3. 从纯⽂本⽂件搜索某个字符串,如ffff00
⽆需安装第三⽅库,使⽤内置库binascii即可
analysis.py
#!/usr/bin python3
# -*- coding: utf-8 -*-
import binascii
def analysis(bin_path:str, out_txt_path:str):
with open(bin_path,'rb')as f:
# 读取全部⾏
all_data = f.readlines()
with open(out_txt_path,'a+')as new_f:
for i in all_data:
# ⼆进制(bytes)类型转换成⼗六进制类型
hex_str = binascii.b2a_hex(i).decode('unicode_escape')
# 以str格式逐⾏写⼊到⽂本
new_f.write(str(hex_str)+'\n')
print("解析完成")
if __name__ =='__main__':
input_file_path ="./kill.bin"
out_file_path ="./hex_"
analysis(input_file_path, out_file_path)
find.py
#!/usr/bin python3
# -*- coding: utf-8 -*-
def search(txt_path:str, key_word:str, target_segment_length:int):
target_txt_dict ={}
target_result_list =[]
state =False
with open(txt_path)as f:
for index, line in adlines()):
python怎么读取py文件
if key_word in line:
target_txt_dict[index +1]= line
state =True
# print(target_txt_dict)
if not state:
print(f"未在⽂件中发现{key_word}")
else:
for k, v in target_txt_dict.items():
if v.find(key_word)!=-1:
find_start_index =0
while1:
target_txt_index = v.find(key_word, find_start_index)
segment_start_index = target_txt_index +len(key_word)
target_data = v[segment_start_index:segment_start_index + target_segment_length] target_result_list.append(target_data)
find_start_index = segment_start_index
if v.find(key_word, find_start_index)==-1:
break
print(target_result_list)
print("查完成")
if __name__ =='__main__':
search_txt ='ffff00'
file_path ="./hex_"
search(file_path, search_txt,16)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论