python - 如何在Python中使用configparser向ini添加节和值?

标签 python configparser

我想问为什么使用我的代码创建的ini文件是空的。 我打算在与 py 文件相同的目录中创建一个 ini 文件。 至此ini已经生成,但是是空的。

import os
import configparser

config = configparser.ConfigParser

#directory of folder
testdir = os.path.dirname(os.path.realpath(__file__))
#file directory
newdir = testdir + "\\test99.ini"

#config ini
config.add_section('testdata')
config.add_section('testdata2')
config.set('testdata','val', '200')
config.set('testdata2','val', '300')

#write ini
newini = open(newdir, 'w')
config.write(newini)
newini.close

最佳答案

您缺少一些括号并导入了错误的内容。咨询documentation .

import os
import configparser

config = configparser.RawConfigParser()

#directory of folder
testdir = os.path.dirname(os.path.realpath(__file__))
#file directory
newdir = testdir + "/test.ini"

#config ini
config.add_section('testdata')
config.add_section('testdata2')
config.set('testdata','val', '200')
config.set('testdata2','val', '300')

#write ini
with open(newdir, 'w') as newini:
    config.write(newini)

关于python - 如何在Python中使用configparser向ini添加节和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49062073/

相关文章:

python - 使用索引的 Numpy 数组索引

python - Pycharm 无法识别 shell 可以识别的包。 Django

python - 没有名为 "backport.configparser"的模块

python - 如何使用 python 从 config.ini 文件中的选项获取嵌套值

python-2.7 - 在Python 2.7中手动构建ConfigParser的深拷贝

python - 仅保存配置(如果更改)

python - 在 python odoo 中格式化字符串

python - 种子选项 : Using different packages for machine learning in Python

python - 如何跨多个 celeryd 进程跟踪已撤销的任务

python ConfigParser读取文件不存在