zoukankan      html  css  js  c++  java
  • python读配置文件,根据配置文件内容改写二进制文件

    import os
    import shutil
    import configparser
    import struct
    
    #全局变量,整个周期都要使用
    manufacture = 'default'
    index_manufacture =  1
    length_manufacture = 0
    
    #配置文件解析函数
    def ParseConfigFile():
        # 必须global声明,否则认为该变量是函数内部重新定义的局部变量
        global length_manufacture
        global manufacture
        conf = configparser.ConfigParser()
        # 若配置文件不存在,生成一个配置文件
        # conf.add_section('config')
        # conf.set('config', 'manufacture', 'YZWF-WF-002')
        # with open('config.ini', 'w') as fw:
        #     conf.write(fw)
        # 读取配置文件
        conf.read('config.ini')
        # 读厂商信息
        manufacture = conf.get('config', 'manufacture')
        length_manufacture = len(manufacture)
    
    # 数据字段替换函数
    def ReplaceFileData(dstfp, datatype):
        if datatype=="manufacture":
            for char in manufacture:
                replaceData = ord(char)
                dstfp.write(struct.pack('B', replaceData))
        else:
            print("not surrport replace!")
    
    # 文件拷贝函数
    def mycopyfile(srcfile, dstpath):
        if not os.path.isfile(srcfile):
            print("%s not exist!" % (srcfile))
        else:
            fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
            if not os.path.exists(dstpath):
                os.makedirs(dstpath)  # 创建路径
            shutil.copy(srcfile, "copy_" + dstpath + fname)  # 复制文件
            print("copy %s -> %s" % (srcfile,"copy_" + dstpath + fname))
    
    # 生成目标文件
    def GenerateTargetFile(parsebytes):
        index = 0
        data_len = len(parsebytes)
        with open("target_fru.bin", 'wb')as fp:
                #若index为替换内容的index,则进行替换
                while(index<data_len):
                    if index==index_manufacture:
                        ReplaceFileData(fp, "manufacture")
                        index = index+length_manufacture
                    else:
                        fp.write(struct.pack('B', parsebytes[index]))
                        index = index+1
    
    
    if __name__ == '__main__':
        #复制一个文件,在该文件上进行操作。
        #mycopyfile("./fru.bin","./")
        ParseConfigFile()
        fp=open("fru.bin",'rb')
        srcData = fp.read()
        GenerateTargetFile(srcData)
        fp.close()
    
    
    
  • 相关阅读:
    一、计算机网络概述
    一些早期的sftp在openssh升级到 openssh7可能闪断解法
    ssh: error while loading shared libraries: libcrypto.so.1.0.0
    PHP Warning: imagettftext(): Problem loading glyph in
    compile pcre on vs2008
    《祝总骧312经络锻炼法》
    神秘的经络
    益嗅上清汤
    鼻病 《仁术便览》
    鼻(附嚏)《医述》
  • 原文地址:https://www.cnblogs.com/retry/p/13935471.html
Copyright © 2011-2022 走看看