关于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字符串
posted @ 2021-01-25 11:19  ReluStarry  阅读(3864)  评论(0编辑  收藏  举报