Python 配置文件config.ini用法详解
1、介绍config.ini文件
config.ini是一种配置文件,常用于存储程序或系统的配置信息。它通常采用键值对的形式,每一行表示一个配置项,用等号(=)将键和值分隔开。config.ini文件可以包含多个节(section),每个节可以包含多个配置项
(图片来源网络,侵删)
2、创建config.ini文件
有两种方法:
1、手动创建config.ini文件
2、在调用写入信息到config.ini文件时会自动创建
[database] host = localhost port = 5432 username = myusername password = mypassword [api] key = myapikey url = https://api.example.com
ini结构:
`片段(section)对应 [database]`
`选项(option)对应 key1,相当于host`
`值(value)对应value1,相当于locahost`
3、写入 config.ini文件
import configparser
def create_config():
config = configparser.ConfigParser()
# 设置database部分
config['database'] = {
'host': 'localhost',
'port': '5432',
'username': 'myusername',
'password': 'mypassword'
}
# 设置api部分
config['api'] = {
'key': 'myapikey',
'url': 'https://api.example.com'
}
# 写入到文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
create_config()
这段代码创建了一个名为 config.ini 的文件,并填充了它与我们在之前的INI文件示例中看到的相同的值。
4、读取config.ini文件
简单版:
import configparser
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
# 读取数据库配置
db_host = config.get('database', 'host')
db_port = config.get('database', 'port')
db_username = config.get('database', 'username')
db_password = config.get('database', 'password')
# 读取API配置
api_key = config.get('api', 'key')
api_url = config.get('api', 'url')
return db_host, db_port, db_username, db_password, api_key, api_url
db_host, db_port, db_username, db_password, api_key, api_url = read_config()
print("Database 数据:")
print(f"Host: {db_host}")
print(f"Port: {db_port}")
print(f"Username: {db_username}")
print(f"Password: {db_password}")
print("\nAPI 数据:")
print(f"Key: {api_key}")
print(f"URL: {api_url}")
Database 数据: Host: localhost Port: 5432 Username: myusername Password: mypassword API 数据: Key: myapikey URL: https://api.example.com Process finished with xit code 0
优化版:
import configparser
import os
# 读取配置文件
def read_config():
# 获取当前文件所在目录
root_dir = os.path.dirname(os.path.dirname(__file__))
# 组装config.ini路径,也可以直接写配置文件的具体路径,不用自动获取
config_dir = os.path.join(root_dir, 'config', 'config.ini')
# 创建configparser对象
cf = configparser.ConfigParser()
# 读取config.ini
cf.read(config_dir, encoding="utf-8")
return cf
cf = read_config()
api_url = cf.get('api', 'url')
# 注意端口要用getint方法获取
database_port = cf.getint('database', 'port')
print(api_url)
print(database_port)
https://api.example.com 5432 Process finished with exit code 0
5、总结:
读取配置文件的常用方法:
# 创建configparser对象
cf = configparser.ConfigParser()
# 读取配置文件 常用的方法介绍
cf.read(filename) # 读取文件,返回filename的list
cf.sections() # 获取配置文件中所有sections的list
cf.options(section) # 获取指定section的键值list
cf.items(section) # 获取指定section下所有的键值对list
cf.get(section, key) # 获取指定section下指定key的value值, 返回str
cf.getint(section, key) # 获取指定sections下指定key的value值, 返回int
cf.getfloat(section, key) # 获取指定sections下指定key的value值, 返回float
cf.getboolean(section, key) # 获取指定sections下指定key的value值, 返回boolean
cf.has_section(section) # 获取是否包含某个section,返回boolean
cf.has_option(section,key) # 获取是否包含某个section的某个键,返回boolean
写入配置文件的常用方法:
# 写入配置文件 常用方法介绍 cf = configparser.ConfigParser() # 实例化对象 cf.read(self.filename) # 读取文件,如果是重新写入,覆盖原有内容不需要读取 cf.add_section(section) # 添加sections值 cf.set(section, option, value) # 在指定的sections中添加键值对 cf.remove_section(section) # 移除sections, 需要先cf.read(filename) cf.remove_option(section, option) # 移除指定sections下的options, 需要先cf.read(filename)
样例介绍:
# 样例介绍
class WriteConfig():
"""写入config文件"""
def __init__(self, filename, filepath=r"D:\python_file\boke\config"):
self.filename = filename
os.chdir(filepath)
self.cf = configparser.ConfigParser()
self.cf.read(self.filename) # 如果修改,则必须读原文件
def _with_file(self):
# write to file
with open(self.filename, "w+") as f:
self.cf.write(f)
def add_section(self, section):
# 写入section值
self.cf.add_section(section)
self._with_file()
def set_options(self,section, option, value=None):
"""写入option值"""
self.cf.set(section, option, value)
self._with_file()
def remove_section(self, section):
"""移除section值"""
self.cf.remove_section(section)
self._with_file()
def remove_option(self, section, option):
"""移除option值"""
self.cf.remove_option(section, option)
self._with_file()
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
