05-2 | python处理ini文件

逸兴
逸兴
逸兴
57
文章
25
评论
2020-04-2222:03:01
评论
3322字阅读11分4秒
摘要

python处理ini文件

ini文件结构

05-2 | python处理ini文件

configparser 模块

python中可使用configparser 处理ini文件,在configparser 中ini本质上被当做一个嵌套字典来处理,如:

05-2 | python处理ini文件
# encoding = utf-8
__author__ = "hugbg.com"

from configparser import ConfigParser

filename = "test.ini"
cfg = ConfigParser()        # 先实例化一个对象
cfg.read(filename)       # 读入文件

# 获取所有的 section
for value in cfg:
    print(value)

# 获取的section name 以及 section 对象
for k,v in cfg.items():
    print(type(k), k, type(v), v)
print()

# 获取section 以及包含的字段,返回的是一个列表,元组格式返回kv对
for k,v in cfg.items():
    print(k, cfg.items(k))

for k in cfg.sections():   # 获取所有section 不包含 DEFAULT
    print(k)
    print(cfg.options(k))   # 获取section中的所有key,所有key中依然包括DEFAULT
print()

print(cfg.has_section('tttt'))      # 判断是否有这个section
print(cfg.has_option('mysql', 'port'))      # 判断这个section 中是否有这个option(缺失值也算)
print('------------------------')


# 获取 section 下 option 的值
x = cfg.get('mysqld', 'port')
print(type(x), x)       # 纯文本文件都是字符串类型
# 可以指定数据类型
y = cfg.getint('mysqld', 'port')
print(type(y), y)
# 获取布尔型
z = cfg.getboolean('mysql', 'testbl')
print(type(z), z)
print()

# 获取value 设置默认值, 获取mysql 下的 ttt 的值,如果没有则设置aaa,这里设置的值,可以是任意类型
print(cfg.get('mysql', 'ttt', fallback='aaa'))
print('------------------------')

if cfg.has_section('t1'):
    cfg.remove_section('t1')

# 增加section, 这里的操作都是在内存中进行的,增加完之后,需要手动写一下文件
cfg.add_section('t1')
cfg.set('t1', 'k1', 'v1')
print(cfg.get('t1', 'k1'))

with open(filename, 'w+', encoding='utf-8') as f:
    cfg.write(f)


# 本质双层字典结构=== {'mysql':{'port': 3306}}---> {section: {option: value}}
print(cfg['mysqld']['port'])
cfg['t2'] = {'k2': 'v2'}       # 通过嵌套字典结构,写入section ,option
print(cfg.get('t2', 'k2'))
cfg['t3'] = {'k3': 'v3', 'k4': 'v4'}    # 同时写入多个 option
print(cfg['t3']['k4'])
print('-------------------------------------')

# 关于缺省值, 如果section 中没有option 则适用DEFAULT。如果有,则优先适用option
cfg.set('t1', 'name', '100')    # 纯文本文件中,输入必须都是字符串格式
print(cfg.get('t1', 'name'))
print(cfg.get('t2', 'name'))
with open(filename, 'w+', encoding='utf-8') as f:
    cfg.write(f)

输出结果

H:\python-stu\venv\Scripts\python.exe H:/pystu-N27/ini文件处理/test.ini.py
DEFAULT
mysqld
mysql
mysqldump
t1
t2
t3
<class 'str'> DEFAULT <class 'configparser.SectionProxy'> <Section: DEFAULT>
<class 'str'> mysqld <class 'configparser.SectionProxy'> <Section: mysqld>
<class 'str'> mysql <class 'configparser.SectionProxy'> <Section: mysql>
<class 'str'> mysqldump <class 'configparser.SectionProxy'> <Section: mysqldump>
<class 'str'> t1 <class 'configparser.SectionProxy'> <Section: t1>
<class 'str'> t2 <class 'configparser.SectionProxy'> <Section: t2>
<class 'str'> t3 <class 'configparser.SectionProxy'> <Section: t3>

DEFAULT [('name', 'test')]
mysqld [('name', 'test'), ('port', '3306'), ('pid-file', '/var/run/mysqld/mysqld.pid'), ('socket', '/var/run/mysqld/mysqld.sock')]
mysql [('name', 'test'), ('innodb_lock_wait_timeout', '120'), ('innodb_file_per_table', '0'), ('testbl', 'True')]
mysqldump [('name', 'test'), ('max_allowed_packet', '2M')]
t1 [('name', '100'), ('k1', 'v1')]
t2 [('name', 'test'), ('k2', 'v2')]
t3 [('name', 'test'), ('k3', 'v3'), ('k4', 'v4')]
mysqld
['port', 'pid-file', 'socket', 'name']
mysql
['innodb_lock_wait_timeout', 'innodb_file_per_table', 'testbl', 'name']
mysqldump
['max_allowed_packet', 'name']
t1
['k1', 'name']
t2
['k2', 'name']
t3
['k3', 'k4', 'name']

False
False
------------------------
<class 'str'> 3306
<class 'int'> 3306
<class 'bool'> True

aaa
------------------------
v1
3306
v2
v4
-------------------------------------
100
test

Process finished with exit code 0

测试文件 test.ini

[DEFAULT]
name = test

[mysqld]
port = 3306
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock

[mysql]
innodb_lock_wait_timeout = 120
innodb_file_per_table = 0
testbl = True

[mysqldump]
max_allowed_packet = 2M

[t2]
k2 = v2

[t3]
k3 = v3
k4 = v4

[t1]
k1 = v1
name = 100



https://www.hugbg.com/archives/2362.html
逸兴
  • 本文由 发表于 2020-04-2222:03:01
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
01-1 数据类型 基础语法

01-1 数据类型

第一章 数据类型 使用type() 函数可以查看数据类型 1.1 字符串 str 字符串是使用单引号或双引号括起来的任意文本。 比如'abc', '123'等 字符串类型 字符串类型用str表示 st...
09-5 | asyncio基本使用 并发编程

09-5 | asyncio基本使用

第一节 关于asyncio asyncio 在3.4 版本中加入到标准库, asyncio基于selector实现, 看似库, 其实是个框架, 包含异步IO, 事件循环, 协程, 任务等内容。 通过a...
09-4 | 全局解释器锁 & 多进程 & 池 并发编程

09-4 | 全局解释器锁 & 多进程 & 池

GIL CPython 在解释器进程级别有一把锁,叫做GIL,即全局解释器锁。 GIL 保证CPython进程中,只有一个线程执行字节码。甚至是在多核CPU的情况下,也只允许同时只能 有一个CPU核心...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: