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
复制代码

打印结果:

 

 

posted @   Syw_文  阅读(7162)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-06-06 Jmeter-----邮件观察仪
点击右上角即可分享
微信分享提示