zoukankan      html  css  js  c++  java
  • python ini文件内容的读取

    (1)新建一个项目,再次新建一个文件 test_cfg.ini

             

     (2)再次新建 get_test_cfg.py用来读取/写入/更改 ini的文件内容

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:lucky,time:2019-06-10
    
    import ConfigParser
    
    cfg1 = "test_cfg.ini"
    
    conf = ConfigParser.ConfigParser()
    conf.read(cfg1)
    
    #读取ini文件中的内容
    print conf.get("email","smtp_server")
    print conf.get("Account information","username")
    print conf.items("Account information")  #获取到Account information中的所有内容,返回字典类型
    print conf.options("Account information")   #获取到Account information中的变量名
    
    #向ini中添加内容
    print conf.add_section("Account")
    print conf.set("Account","title","1")
    print conf.write(open("test_cfg.ini","w+"))
    
    #向ini中修改内容
    conf.set("Account","title","6")
    conf.write(open("test_cfg.ini","w+"))

    如上是最简单的方式,另外一个方式是,我们可以将读取配置文件的信息单写一个py文件,再从需要调用的py文件中直接读取即可,详见如下:

    (1)新建 read_test_cfg.py 文件

         

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:lucky,time:2019-06-10
    
    import ConfigParser
    
    cfg1 = "test_cfg.ini"
    
    conf = ConfigParser.ConfigParser()
    conf.read(cfg1)
    
    #读取ini文件中的内容
    smtp_server = conf.get("email","smtp_server")
    username = conf.get("Account information","username")

     

    (2)新建 test.py 文件

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:lucky,time:2019-06-10
    
    
    import read_test_cfg
    
    smtp = read_test_cfg.smtp_server
    user = read_test_cfg.username
    
    
    print smtp
    print user

    打印结果:

     

  • 相关阅读:
    Python内置的操作系统模块(os)与解释器交互模块(sys)
    Python常用模块-常见的加密算法模块使用
    Python常用模块-随机数模块(random)
    Python常用模块-时间模块(time&datetime)
    Python递归函数介绍
    Python内置函数之匿名(lambda)函数
    Python远程连接模块-Telnet
    Python的常用内置函数介绍
    Python的生成器进阶玩法
    Python中的列表解析和生成器表达式
  • 原文地址:https://www.cnblogs.com/syw20170419/p/10983744.html
Copyright © 2011-2022 走看看