【发布时间】:2019-11-20 08:59:17
【问题描述】:
我在 ini 文件中添加了部分及其值,但 configparser 不想打印我总共有哪些部分。我做了什么:
import configparser
import os
# creating path
current_path = os.getcwd()
path = 'ini'
try:
os.mkdir(path)
except OSError:
print("Creation of the directory %s failed" % path)
# add section and its values
config = configparser.ConfigParser()
config['section-1'] = {'somekey' : 'somevalue'}
file = open(f'ini/inifile.ini', 'a')
with file as f:
config.write(f)
file.close()
# get sections
config = configparser.ConfigParser()
file = open(f'ini/inifile.ini')
with file as f:
config.read(f)
print(config.sections())
file.close()
返回
[]
类似的代码是in the documentation,但不起作用。我做错了什么以及如何解决这个问题?
【问题讨论】:
-
仅供参考,
with语句将为您关闭它,因此无需分配给变量文件。只需使用with open("...", "a") as f:并删除close()。 -
从文档中,
config.read接受 文件名,而不是文件描述符对象。 IE。config.read("ini/inifile.ini")。如果要使用文件描述符对象,请改用config.read_file(f)。 -
@alkasm 谢谢!您可以将其写为关闭问题的答案
标签: python configparser