• 关于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字符串
  • 相关阅读:
    ExtJS 4布局
    ExrJS4学习笔记1 类
    Jquery实现动态添加按钮
    ExtJs 4 MVC
    读取目录下所有目录和文件加载到TreeView
    利用List的Sort()、Find()、FindAll()、Exist()來解決一些問題
    html常用
    ExtJs3.3 TreePanel,checked节点和平常节点同时存在
    sql server 常用查询
    美女时钟网页代码
  • 原文地址:https://www.cnblogs.com/relustarry/p/14324215.html
Copyright © 2020-2023  润新知