關於Python對文件字節流數據的處理


關於Python對文件字節流數據的處理

讀取文件的字節流數據,將其轉換為十六進制數據

def read_file(): with open('./flag.zip','rb') as file_byte: file_hex = file_byte.read().hex() print(file_hex) write_file(file_hex) def write_file(file_hex): with open('new.txt','w') as new_file: new_file.write(file_hex) if __name__ == '__main__': read_file() 

讀取文件的字節流數據,將其編碼為base64並輸出

import base64 def read_file(): with open('./flag.zip','rb') as file_byte: file_base64 = base64.b64encode(file_byte.read()) print(file_base64) if __name__ == '__main__': read_file()

將十六進制文件轉化為字節流文件寫入

import struct a = open("str.txt","r")#十六進制數據文件 lines = a.read() res = [lines[i:i+2] for i in range(0,len(lines),2)] with open("xxx.xxx","wb") as f: for i in res: s = struct.pack('B',int(i,16)) f.write(s)

binascii.b2a_hex()binascii.hexlify():將字節類型字符串數據轉換為十六進制數據

>>> import binascii >>> text=b'flag{MoChu7_Need_A_Girlfriend}' >>> binascii.b2a_hex(text) b'666c61677b4d6f436875375f4e6565645f415f4769726c667269656e647d' >>> binascii.hexlify(text) b'666c61677b4d6f436875375f4e6565645f415f4769726c667269656e647d' 

 

binascii.a2b_hex()binascii.unhexlify():將十六進制數據轉換位字節類型字符串數據

>>> import binascii >>> hex_str='666c61677b4d6f436875375f4e6565645f415f4769726c667269656e647d' >>> binascii.a2b_hex(hex_str) b'flag{MoChu7_Need_A_Girlfriend}' >>> binascii.unhexlify(hex_str) b'flag{MoChu7_Need_A_Girlfriend}' 

 

import binascii with open('./xxx.xxx','r') as file: with open('xxx.xxx','wb') as write_file: write_file.write(binascii.unhexlify(file.read())) 

 

如果碰到是圖片字節流的base64編碼,可以在瀏覽器中使用

data:image/png;base64,這里添加base64字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM