要修改一个 ini 文件中的字典数据,你可以使用 configparser 模块来读取和修改 ini 文件。

首先,你需要导入 configparser 模块:

import configparser

接下来,你可以创建一个 configparser 对象,并使用它来读取 ini 文件:

config = configparser.ConfigParser()
config.read('file.ini')

假设 ini 文件的内容如下:

[section]
key1 = value1
key2 = value2

你可以使用 get 方法来获取字典数据:

data = config.get('section', 'key1')

要修改字典数据,你可以使用 set 方法:

config.set('section', 'key1', 'new_value1')

最后,你可以使用 write 方法将修改后的数据写回到 ini 文件中:

with open('file.ini', 'w') as configfile:
    config.write(configfile)

完整的代码如下:

import configparser

config = configparser.ConfigParser()
config.read('file.ini')

data = config.get('section', 'key1')
print(data)

config.set('section', 'key1', 'new_value1')

with open('file.ini', 'w') as configfile:
    config.write(configfile)

运行此代码后,ini 文件将会被修改,并且 key1 的值将会被更新为 "new_value1"

python 字典数据 修改 ini原有数据

原文地址: https://www.cveoy.top/t/topic/hLb4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录