今天我们将探讨如何操作ini配置文件,首先介绍读操作。
Part 1:场景描述
在开发和生产环境中,某些信息如IP地址会有所不同。一个有效的解决方案是将这些信息存储在配置文件中,如ini文件。当然,这些信息也可以存储在数据库中,但对于简单的信息,使用ini文件更为简便。ini文件,即Initialization File,实际上是一个格式为ini的文本文件。在Pycharm中,可以安装插件来方便地可视化展示ini文件。

Part 2:代码
立即学习“Python免费学习笔记(深入)”;
代码语言:Python 代码运行次数:0
import os
import configparser
current_path = os.path.dirname(os.path.abspath(__file__))
init_file_address = os.path.join(current_path, 'configuration.ini')
conf = configparser.ConfigParser()
conf.read(init_file_address, encoding='utf-8')
result1 = conf.get('connect_info', 'host')
print('result1=', result1)
result2 = conf.get('address_info', 'address')
print('result2=', result2)
result3 = conf.get('test3', 'host')
print('result3=', result3)代码截图

执行结果

Part 3:部分代码解读
current_path = os.path.dirname(os.path.abspath(__file__))
init_file_address = os.path.join(current_path, 'configuration.ini')
conf = configparser.ConfigParser()
ConfigParser
conf.read(init_file_address, encoding='utf-8')
result1 = conf.get('connect_info', 'host')[connect_info]
host
[connect_info]
host
get
result2 = conf.get('address_info', 'address')#
以上就是Python-ini文件-01-读操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号