1、配置文件configparser模块
此模块可以对ini、cfg格式的配置文件进行读写操作,下面内容是我从一个游戏插件的ini配置文件中提取出来的部分内容:
[Settings]
Version=1.980
UseGrimCamDll=True
ShowMainMenuGimmick=True
LootBeam=True
HideFloatingCombatAttr=False
[HealthBarPlayerPets]
PetHealthBarThreshold=100.000
Width=50
Height=10
LifeMaxBar.A=0.500
[Configurator]
VK_F1=112
VK_F5=116
ScaleFactor=2.00
[Lua]
Logging=True
[CrucibleMod]
ModName=
active=False
由于这模块名字太长了,先起个别名,后续看着好看点:
>>> import configparser
>>> config = configparser.ConfigParser() # 起别名短点
>>> config.read(r'C:\Users\AERO\PycharmProjects\pythonProject1\hihi.ini', encoding='utf-8')
['C:\\Users\\AERO\\PycharmProjects\\pythonProject1\\hihi.ini']
# 先读完整个配置文件,模块才能对其进行读写!
1.1、读配置文件
1.1.1、查看所有section标题
config.sections()
# 读出来的sections以列表形式存在
['Settings', 'HealthBarPlayerPets', 'Configurator', 'Lua', 'CrucibleMod']
1.1.2、获取section所有option
# option即选项,类似字典的key!
>>> config.options('Configurator')
['vk_f1', 'vk_f5', 'scalefactor']
1.1.3、获取section所有option的值
# 相当于字典取得所有key与value
>>> config.items('Configurator')
[('vk_f1', '112'), ('vk_f5', '116'), ('scalefactor', '2.00')]
1.1.4、获取section指定option的值
# 类似字典取得某个key所对应的值,返回的值为str
>>> config.get('Configurator', 'scalefactor')
'2.00'
1.1.5、转换section指定option的值为int
# 上面说到返回的值是str,若想返回值为int,用getint,其实就是get后调用int!
>>> config.getint('Configurator', 'vk_f5')
116
1.1.6、查看section指定option返回布尔型
# Lua标题下,logging选项的值是布尔型,如果不是会报错!
>>> config.getboolean('Lua', 'Logging')
True
1.1.7、查看section指定option返回浮点型
# 同上,不是浮点型则报错!
>>> config.getfloat('Settings', 'Version')
1.98
1.2、修改配置文件
1.2.1、删除整个section
>>> config.remove_section('CrucibleMod')
True
# 可以看到,该section已经人间蒸发!
>>> config.sections()
['Settings', 'HealthBarPlayerPets', 'Configurator', 'Lua']
1.2.2、删除section指定option
>>> config.remove_option('Configurator', 'ScaleFactor')
True
# ScaleFactor已人间蒸发
>>> config.items('Configurator')
[('vk_f1', '112'), ('vk_f5', '116')]
1.2.3、判断section是否存在
# 上面演示把它删除了
>>> config.has_section('CrucibleMod')
False
1.2.4、判断option是否存在
>>> config.has_option('Configurator', 'ScaleFactor')
False
1.2.5、添加section
>>> config.add_section('Building')
# 已添加
>>> config.sections()
['Settings', 'HealthBarPlayerPets', 'Configurator', 'Lua', 'Building']
1.2.6、为section添加option
# 第一个参数为section,第二为option,第三为option的值
>>> config.set('Building', 'name', 'sanxi')
# 已添加
>>> config.items('Building')
[('name', 'sanxi')]
1.2.7、将修改后的值写入文件
# 因为此前是将文件内容read到内存,所以改的全部是内存的数据,如果要保存,需要写入到磁盘文件!
>>> with open (r'C:\Users\AERO\PycharmProjects\pythonProject1\new.ini', 'w') as config_file:
... config.write(config_file)
1.3、新建配置文件
import configparser
config = configparser.ConfigParser()
config["[Settings]"] = {'Version': '1.980',
'UseGrimCamDll': 'True',
'LootBeam': 'True'}
config["HealthBarPlayerPets"] = {"PetHealthBarThreshold": "100.000"}
with open(r'GrimDawn.ini', 'wt', encoding='utf-8') as config_file:
config.write(config_file)
执行得到结果,打开GrimDawn.ini,内容如下
[Settings]
version = 1.980
usegrimcamdll = True
lootbeam = True
[HealthBarPlayerPets]
pethealthbarthreshold = 100.000