python ini文件内容的读取

本文详细介绍使用Python的ConfigParser模块来读取、写入和修改INI配置文件的方法。通过实例演示了如何获取INI文件中的内容,添加和修改配置项,并展示了如何在不同Python文件间共享配置信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(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

打印结果:

 

 

转载于:https://www.cnblogs.com/syw20170419/p/10983744.html

### 如何在 Python 中从 INI 文件读取 Section 为了实现从 INI 文件读取特定部分的内容,在 Python 中可以利用 `configparser` 库中的 `SafeConfigParser` 类来解析配置文件。此方法适用于处理标准格式的 INI 配置文件。 创建并初始化一个 `SafeConfigParser` 对象之后,通过调用其 `read()` 方法加载指定路径下的 INI 文件[^1]: ```python import configparser # 创建 SafeConfigParser 实例 config = configparser.SafeConfigParser() # 加载 INI 文件 file_path = 'example.ini' config.read(file_path) ``` 一旦成功加载了 INI 文件,则可以通过访问字典样式的属性获取所需的部分名称对应的键值对集合。例如要取得名为 `[section_name]` 的节数据,可按如下方式操作: ```python # 获取整个 section 下的所有 key-value 键值对 items_in_section = config.items('section_name') for key, value in items_in_section: print(f'{key}: {value}') ``` 如果仅需获得某个具体项的值,那么可以直接使用 `get()` 函数,并传入目标 section 和 option 名称作为参数[^5]: ```python specific_option_value = config.get('section_name', 'option_name') print(specific_option_value) ``` 对于那些可能不存在于某些较老版本 Python 或者其他环境中的模块导入问题,建议采用兼容性更强的方式引入所需的库[^2]: ```python try: import configparser except ImportError: from six.moves import configparser as ConfigParser ``` 上述代码片段展示了如何优雅地解决不同环境中存在的差异性问题,从而确保程序可以在更广泛的范围内正常运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值