当前位置 : 主页 > 编程语言 > python >

Python从门到精通(五):文件处理-06-ini文件处理

来源:互联网 收集:自由互联 发布时间:2022-06-27
这种类型的文件一般在脚本等一些工具程序中用处比较多,唯一一点注意的是ini的key不区分大小写。 文件内容 [ installation ] library = % ( prefix ) s / lib include = % ( prefix ) s / include bin = % ( p

这种类型的文件一般在脚本等一些工具程序中用处比较多,唯一一点注意的是ini的key不区分大小写。

文件内容

[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local

# Setting related to debug configuration
[debug]
log_errors=true
show_warnings=False

[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
signature:
=================================
Brought to you by the Python Cookbook
=================================

操作文件

from configparser import ConfigParser

cfg = ConfigParser()
cfg.read('test.ini')

print(f'sections is: {cfg.sections()}')
print(f"library is: {cfg.get('installation','library')}")
print(f"log errors: {cfg.getboolean('debug','log_errors')}")
print(f"port is: {cfg.getint('server','port')}")
print(f"nworkers is: {cfg.getint('server','nworkers')}")
print(f"signature is: {cfg.get('server','signature')}")
#修改
cfg.set('server','port','9000')
cfg.set('debug','log_errors','False')

print(f"new debug is: {cfg.getboolean('debug','log_errors')}")
print(f"After change,port is: {cfg.getint('server','port')}")

print(cfg.get('installation','PREFIX'))
print(cfg.get('installation','prefix'))sections is: ['installation', 'debug', 'server'] #配置文件分组,注意看.ini中的内容
library is: /usr/local/lib
log errors: True
port is: 8080
nworkers is: 32
signature is:
=================================
Brought to you by the Python Cookbook
=================================
new debug is: False
After change,port is: 9000
/usr/local
/usr/local
网友评论