如果多次执行ConfigParser
config.add_section('main')
,则针对同一文件是否会导致出现错误,例如具有多个main
部分,或者如果已经存在则跳过创建部分?
Quoting the documentation of configparser.ConfigParser.add_section
:
add_section(section)
Add a section named section to the instance. If a section by the given name already exists,DuplicateSectionError
is raised.
ConfigParser
object can be seen as a dictonary (section) of dictionaries (option/option values).
Using add_section
twice on the same name raises an exception
import configparser
s = configparser.ConfigParser()
s.add_section("main")
s.add_section("main")
gives:
configparser.DuplicateSectionError: Section 'main' already exists
workaround check if section exists, add only if it doesn't:
def add_section_no_matter_what(s,section_name):
if not s.has_section(section_name):
s.add_section(section_name)
useful in an helper function to create section if not already exists, else use the existing one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.