Python3如何读取toml配置文件-创新互联

这篇文章主要介绍Python3如何读取toml配置文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

创新互联专注于企业全网营销推广、网站重做改版、贵定网站定制设计、自适应品牌网站建设、HTML5商城建设、集团公司官网建设、外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为贵定等各大城市提供网站开发制作服务。

【toml 简介】

   TOML是前GitHub CEO, Tom Preston-Werner,于2013年创建的语言,其目标是成为一个小规模的易于使用的语义化配置文件格式。TOML被设计为可以无二义性的转换为一个哈希表(Hash table)。

  官方中文介绍在这里:https://github.com/toml-lang/toml/tree/master/versions/cn

  walker 下面使用的第三方解析包是:https://pypi.org/project/toml/

【config.toml】

# 输入目录
SrcRoot = 'D:\test\input'

# 输出目录
DstRoot = 'D:\test\output'

【t.py】

#encoding: utf-8
#author: walker
#date: 2018-12-11
#summary: 读取 UTF-8/UTF-8-BOM 格式的 toml 配置文件
import os
import sys
import toml
SrcRoot = r''
DstRoot = r''
#读取配置文件
def ReadConfig():
    global SrcRoot, DstRoot
    cfgFile = 'config.toml'
    if not os.path.exists(cfgFile):
        input(cfgFile + ' not found')
        sys.exit(-1)
    with open(cfgFile, mode='rb') as f:
        content = f.read()
    if content.startswith(b'\xef\xbb\xbf'):     # 去掉 utf8 bom 头
        content = content[3:]
    dic = toml.loads(content.decode('utf8'))
        
    SrcRoot = dic['SrcRoot'].strip()
    if not os.path.exists(SrcRoot):
        print('Error: not exists %s' % SrcRoot)
        sys.exit(-1)
    print('SrcRoot: %s' % SrcRoot)
    
    DstRoot = dic['DstRoot'].strip()
    if not os.path.exists(DstRoot):
        print('Error: not exists %s' % DstRoot)
        sys.exit(-1)
    print('DstRoot: %s' % DstRoot)
        
    print('Read config.toml successed!')
    
if __name__ == '__main__':
    ReadConfig()

【cmd】

D:\Python3Project\test>python3 t.py
SrcRoot: D:\test\input
DstRoot: D:\test\output
Read config.toml successed!

以上是“Python3如何读取toml配置文件”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站栏目:Python3如何读取toml配置文件-创新互联
当前链接:http://ybzwz.com/article/dodiej.html