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()
    
    
    
  • 相关阅读:
    5.6 Go 常用函数
    5.5 Go defer
    5.4 Go 闭包
    5.3 Go 匿名函数
    5.2 Go 包与函数
    python 通过pytz模块进行时区的转换,获取指定时区的时间
    前端在js中获取用户所在地区的时间与时区
    Python2 指定文件编码格式需要注意的地方
    linux 使用进程管理工具 supervisor
    Python 私有变量中两个下划线 _ _item 与 一个下划线的区别 _item
  • 原文地址:https://www.cnblogs.com/retry/p/13935471.html
Copyright © 2011-2022 走看看