python解析配置文件

https://blog.csdn.net/qq_34745295/article/details/79438774

读配置文件,将某个字串对应的asciic码写入bin文件

import configparser
import struct

#加载现有配置文件
conf=configparser.ConfigParser()
#添加section
conf.add_section('config')
#预备要写入配置文件的字段
conf.set('config','host','192.168.1.101')
conf.set('config','user','jiangfeng.zhang')
conf.set('config','passwd','2360838724')
conf.set('config','email','jiangfeng.zhang@aliyun.com')
conf.set('config','asciic','5AX-YZWF-TEST')
#开始写入配置文件,如果文件不存在则创建一个文件
with open('config.ini','w') as fw:
    conf.write(fw)
#读取配置文件
conf.read('config.ini')
#读取配置信息
host=conf.get('config','host')
user=conf.get('config','user')
passwd=conf.get('config','passwd')
email=conf.get('config','email')
asciic=conf.get('config','asciic')
#打印测试输出配置信息
print(host)
print(user)
print(passwd)
print(email)
#print('%x' %(asciic[0]))  打印报错,str类型的变量不能用integer方式打印
print('%x' %ord(asciic[0]))

#下面循环遍历输出对应的asciic
length = len(asciic)
print("获取到配置文件的字符串长度为(length is : )" + str(length))
# 以二进制文件读写,所以此处的读写也应该是bytes类型,not其它类型
with open('hexBin.bin', 'wb')as fp:
    for char in asciic:
        tmp_ASCII = ord(char)
        fp.write(struct.pack('B', tmp_ASCII))
        print(" 0x%x" % tmp_ASCII, end=" ")  # end=" "标识不换行输出




posted @ 2020-11-04 23:11  hostid  阅读(276)  评论(0编辑  收藏  举报