python基础之ini文件操作

一、config.ini 配置文件

[DATABASE]
host = 192.1.1.1
username = root
password = root
port = 3306
database = jforum

[URL]
#ip,端口
ip =127.0.0.1
port= 8089

二、操作ini常用方法

--read():读取配置文件
--sections():读取配置文件中所有的section(如上配置文件:DATABASE,URL)
--options(section):读取该section下所有的option(可以理解成读取该组下的所有key,如options("URL"),值['ip', 'port'])
--items(section):读取该section下的所有key-vaule,并以键值对形式输出(如:sectioitems("URL"),值:[('ip', '127.0.0.1'), ('port', '8089')])
--get(section, option):读取指定section下面的option的值(可以理解成,读取具体某个section下面指定key的值,如config.get('URL','ip')),值:127.0.0.1)
--add_section(section):添加一个section,参数为section的名称
--set(section, option, value):在section下面添加一条数据(key=value)
--add与set需调用write(open(configPath, "a"))才可以写入ini文件 #参数a表示最近,w重写
--remove_seciton(seciton) 删除整个seciton
--config.remove_option(seciton,key) ,删除seciton的某个key值

三、源码举例

#!/usr/bin/python3
# encoding:utf-8
'''
Created on 2020-04-19 23:19
@author: Administrator
'''
import configparser
import os
from turtle import readconfig

#获取文件绝对路径 D:\common\
proDir = os.getcwd()
#拼接文件路径 D:\common\config.ini
configPath = os.path.join(proDir, "config.ini")

#创建管理对象
config = configparser.ConfigParser()
#读取配置类
class readConfig():
    #读取ini文件
    config.read(configPath, encoding="UTF-8")
    #获取所有的section
    @staticmethod
    def get_sections():
        return config.sections()
    @staticmethod
    def get_items(section):
        return config.items(section)
    @staticmethod
    def get_options(section):
        return config.options(section)
    @staticmethod
    def get_Vaule(section,name):
        value = config.get(section, name)
        return value
    @staticmethod
    def add_section():
        config.add_section('HTTP')
    @staticmethod
    def set_section(section, option, value):
        config.set(section, option, value)
    @staticmethod
    def remove_seciton(seciton):
        config.remove_section(seciton)
    @staticmethod
    def remove_seciton_value(seciton,key):
        config.remove_option(seciton,key)      
if __name__=='__main__':
   print('-----1.打印所有section')
   print(readConfig.get_sections())
   print('-----2.打印section=URL的所有key-Value值')
   print(readConfig.get_items("URL"))
   print('-----3.打印section=URL的所有key值')
   print(readConfig.get_options("URL"))
   print('-----4.打印section=URL,key=ip的value值')
   print(readConfig.get_Vaule('URL','ip'))
   print('-----5.新增之后打印所有section,注意有一个新增值HTTP')
   readConfig.add_section()
   print(readConfig.get_sections())
   print('-----6.新增section=HTTP,key=port,value=443,查看值,443为新增的值')
   readConfig.set_section('HTTP', 'port', '443')
   print(readConfig.get_Vaule('HTTP','port'))
   #上面的新增并不会真的真正写入,需加这个才能正在写入ini文件,如果参数为"w"则表示删除文件重新写入,"a"为追加模式写入
   #config.write(open(configPath, "a"))  
   print('-----7.删除sections=URL,打印所有sections,注意URL已被删除')
   readConfig.remove_seciton("URL")
   print(readConfig.get_sections())
   print('-----8.删除sections=DATABASE,key=host,打印所有key值,注意host已被删除')
   readConfig.remove_seciton_value('DATABASE','host')
   print(readConfig.get_options('DATABASE'))

运行结果

-----1.打印所有section
['DATABASE', 'URL']
-----2.打印section=URL的所有key-Value值
[('ip', '127.0.0.1'), ('port', '8089')]
-----3.打印section=URL的所有key值
['ip', 'port']
-----4.打印section=URL,key=ip的value值
127.0.0.1
-----5.新增之后打印所有section,注意有一个新增值HTTP
['DATABASE', 'URL', 'HTTP']
-----6.新增section=HTTP,key=port,value=443,查看值,443为新增的值
443
-----7.删除sections=URL,打印所有sections,注意URL已被删除
['DATABASE', 'HTTP']
-----8.删除sections=DATABASE,key=host,打印所有key值,注意host已被删除
['username', 'password', 'port', 'database']

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中常见的配置文件有多种,包括`.ini`(如`.ini`文件基础)和`.yaml`(如YAML文件基础)。 1. **INI文件**[^1]: - `.ini`文件是Windows系统中常用的一种配置文件格式,可以使用Python内置的`configparser`模块来读写。例如,读取ini文件: ```python import configparser config = configparser.ConfigParser() config.read('config.ini') value = config.get('section', 'option') ``` - 修改ini文件: ```python config.set('section', 'option', 'new_value') with open('config.ini', 'w') as configfile: config.write(configfile) ``` 2. **YAML文件**: - YAML (YAML Ain't Markup Language) 是一种轻量级的数据序列化格式,Python中可以使用`PyYAML`库进行操作。读取yaml文件: ```python import yaml with open('config.yaml', 'r') as file: config_data = yaml.safe_load(file) value = config_data['section']['option'] ``` - 写入yaml文件: ```python data = {'section': {'option': 'new_value'}} with open('config.yaml', 'w') as file: yaml.dump(data, file) ``` 3. **封装操作**: - 对于这两种文件格式的操作,通常会封装成一个模块,以便于项目中复用和管理: ```python class ConfigManager: def __init__(self, file_type, filename): if file_type == 'ini': self.config = configparser.ConfigParser() elif file_type == 'yaml': self.config = yaml.safe_load self.filename = filename def read(self): with open(self.filename, 'r') as file: return self.config(file) def write(self, data): with open(self.filename, 'w') as file: if file_type == 'ini': self.config.write(file) else: yaml.dump(data, file) ``` 这样,你可以根据需要选择`ConfigManager`实例的不同配置文件类型来操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值