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()
    
    
    
  • 相关阅读:
    使用树莓派打造远程WEB服务器
    oracle 12c新建pdb实例
    word标题变成黑色方块解决
    idea 报JDBC连接失败原因之一
    maven项目pom.xml需要的一些配置
    Mysql时区无法识别
    数据库报ORA-12514
    win10无法在桌面右键快捷打开个性化设置、显示设置,在任务栏右键无法快捷打开任务栏设置
    Tomcat部署项目时,发布的项目页面部分乱码,且页面渲染文件也是乱码。
    高性能、高稳定性的跨平台MQTT客户端
  • 原文地址:https://www.cnblogs.com/retry/p/13935471.html
Copyright © 2011-2022 走看看