生活随笔
收集整理的這篇文章主要介紹了
python读取二进制文件,转成十六进制格式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
需求:
讀取二進制(bytes)的文件轉(zhuǎn)換為十六進制(hex),保存到txt純文本文件里從純文本文件搜索某個字符串,如ffff00
無需安裝第三方庫,使用內(nèi)置庫binascii即可
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
:hex_str
= binascii
.b2a_hex
(i
).decode
('unicode_escape')new_f
.write
(str(hex_str
) + '\n')print("解析完成")if __name__
== '__main__':input_file_path
= "./kill.bin"out_file_path
= "./hex_of_kill.txt"analysis
(input_file_path
, out_file_path
)
def search(txt_path
: str, key_word
: str, target_segment_length
: int):target_txt_dict
= {}target_result_list
= []state
= Falsewith open(txt_path
) as f
:for index
, line
in enumerate(f
.readlines
()):if key_word
in line
:target_txt_dict
[index
+ 1] = linestate
= Trueif not state
:print(f"未在文件中發(fā)現(xiàn){key_word}")else:for k
, v
in target_txt_dict
.items
():if v
.find
(key_word
) != -1:find_start_index
= 0while 1: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:breakprint(target_result_list
)print("查找完成")if __name__
== '__main__':search_txt
= 'ffff00'file_path
= "./hex_of_kill.txt"search
(file_path
, search_txt
, 16)
總結(jié)
以上是生活随笔為你收集整理的python读取二进制文件,转成十六进制格式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。