使用configparser模块读取配置文件

 

读取.ini文件

abc.ini

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[com.net]
user = knight

[ip,yeyese.clu]
port = 1010
forwardx11 = no

读取操作

from configparser import ConfigParser


cfgg = ConfigParser()

s = cfgg.read('abc.ini')

print(s)
# 读取配置文件的每个节段
m = cfgg.sections()
print(m)
# 返回字符串
p = cfgg.get('com.net','User')
print(p)
# 返回boolean 值
n = cfgg.getboolean('DEFAULT','Compression')
print(n)
# 返回整型
port = cfgg.getint('ip,yeyese.clu','Port')
print(port)

修改

from configparser import ConfigParser

cfg = ConfigParser()

cfg.read('abc.ini')

cfg.set('ip,yeyese.clu','Port','1010')


with open('abc.ini','w') as f:
    cfg.write(f)

添加

from configparser import ConfigParser

cfg = ConfigParser()

cfg.read('abc.ini')

cfg.add_section('user')
cfg.set('user','lzj','123')
cfg.set('user','hu','123')
cfg.set('user','xing','123')
cfg.set('user','zhuo','123')


with open('abc.ini','w') as f:
    cfg.write(f)

 

 

创建配置文件

 

from configparser import ConfigParser

cfg = ConfigParser()

cfg.read('ab.ini')

cfg.add_section('user')
cfg.set('user','lzj','123')
cfg.set('user','hu','123')
cfg.set('user','xing','123')
cfg.set('user','zhuo','123')


with open('ab.ini','w') as f:
    cfg.write(f)

 

 删除节段

from configparser import ConfigParser

cfg = ConfigParser()

cfg.read('abc.ini')

cfg.remove_section('user')



with open('abc.ini','w') as f:
    cfg.write(f)

 

使用pyyaml 模块读取yml文件

import yaml
import os


# 获取当前脚本所在文件夹路径
curPath = os.path.dirname(os.path.realpath(__file__))
print(curPath)

# 获取yaml文件夹路径
yamlPath = os.path.join(curPath,'nb.yaml')

from pathlib import Path
mypath = Path(yamlPath)
print(mypath)
if not  mypath.exists():
    # windows创建文件命令
    os.popen("type nul>{}".format(yamlPath))
    import time
    time.sleep(1)
print(yamlPath)

f = open(yamlPath,'r',encoding='utf8')

d = yaml.load(f,Loader=yaml.FullLoader) # **
# Loader 如果不加这个参数,会出现警告
print(d)


print(d['nb']['user'])
print(d['redis'])
print(d['redis']['host'])

f.close()