使用configparser读取ini文件需创建configparser对象并调用read()方法,之后可通过字典方式访问配置项,并用getint()、getboolean()等方法转换数据类型;2. 修改配置直接赋值,写入文件需使用with open()打开文件并调用config.write()方法确保文件正确保存;3. 处理注释和空行时,configparser默认忽略;或#开头的行及空行,可自定义comment_prefixes和inline_comment_prefixes设置注释符号;4. 默认section和option名称转为小写,若需保持大小写敏感,应设置optionxform=str;5. 创建新section需调用add_section()方法并检查是否存在以避免duplicatesectionerror,再添加option;6. 避免读取异常应使用has_section()和has_option()预先判断或用try...except捕获keyerror;7. 多线程环境下configparser非线程安全,需使用threading.lock()保证读写操作的互斥性,防止数据竞争和文件损坏。
Python操作INI配置文件,核心在于
configparser
configparser模块
INI配置文件通常用于存储程序的配置信息,例如数据库连接字符串、API密钥、程序运行参数等等。
configparser
立即学习“Python免费学习笔记(深入)”;
首先,你需要创建一个
configparser
read()
import configparser config = configparser.ConfigParser() config.read('config.ini') # 获取某个section下的option值 db_host = config['database']['host'] db_port = config['database'].getint('port') # 确保读取的是整数类型 print(f"数据库主机:{db_host}, 端口:{db_port}")
注意,
getint()
getboolean()
getfloat()
NoOptionError
NoSectionError
try...except
修改配置很简单,直接赋值即可。写入文件则需要使用
write()
config['database']['host'] = 'new_host' config['database']['timeout'] = '15' # 字符串形式 with open('config.ini', 'w') as configfile: config.write(configfile)
这里有个小技巧,写入时最好使用
with open()
config.write()
configparser
;
#
configparser
comment_prefixes
inline_comment_prefixes
config = configparser.ConfigParser(comment_prefixes=('#',), inline_comment_prefixes=(';',))
这会把
#
;
默认情况下,
configparser
configparser
optionxform
str
config = configparser.ConfigParser() config.optionxform = str # 保持大小写
不过,我个人建议还是统一使用小写,这样可以避免很多潜在的错误。
创建新的section使用
add_section()
config.add_section('new_section') config['new_section']['new_option'] = 'new_value' with open('config.ini', 'w') as configfile: config.write(configfile)
记住,创建section之前要检查它是否已经存在,否则会抛出
DuplicateSectionError
读取配置时,最常见的异常是
NoSectionError
NoOptionError
has_section()
has_option()
if config.has_section('database') and config.has_option('database', 'host'): db_host = config['database']['host'] print(f"数据库主机:{db_host}") else: print("数据库配置不存在")
或者,使用
try...except
try: db_host = config['database']['host'] print(f"数据库主机:{db_host}") except KeyError: print("数据库配置不存在")
选择哪种方式取决于你的具体需求和代码风格。
configparser
import threading lock = threading.Lock() def read_config(key): with lock: config = configparser.ConfigParser() config.read('config.ini') return config['section'][key] def write_config(key, value): with lock: config = configparser.ConfigParser() config.read('config.ini') config['section'][key] = value with open('config.ini', 'w') as configfile: config.write(configfile)
使用
threading.Lock()
虽然
configparser
configparser
以上就是Python如何操作INI配置文件?configparser模块的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号