关于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 @   ReluStarry  阅读(3879)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示