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()


posted @ 2020-11-06 10:21  hostid  阅读(294)  评论(0)    收藏  举报