![](/img/trans.png)
[英]How do I create and write headers to a csv file if it doesn't exist, but if it already exists then write data?
[英]How do I automatically create a section if it doesn't exist?
如果我嘗試寫入尚不存在的部分, configparser.NoSectionError
收到configparser.NoSectionError
:
from configparser import ConfigParser
c = ConfigParser()
c['a'] = {'x': 1}
c['a']['y'] = '2'
c.set(section='a', option='z', value='3')
for i in c:
print(f'Section {i}:')
for j in c[i]:
print(f'\t{j}: {c[i][j]}')
# KeyError
c['b']['u'] = '0'
# NoSectionError
c.set('b', 'u', '0')
真的沒有辦法要求ConfigParser
設置一個值,如果它不存在就創建該部分嗎? 檢查一個部分是否存在,並每次都創建它似乎是一個乏味的設計。
這不能直接完成。 但是,存在基於 ConfigParser 對象存在的read_dict
方法的權衡。 這個想法是定義一個只包含部分名稱的假字典,每個部分都與一個空字典相關聯。 這是您之前代碼中插入的技巧:
from configparser import ConfigParser
c = ConfigParser()
c.read_dict({'a':{},'b':{},'c':{}})
c['a']['x'] = '1'
c['a']['y'] = '2'
c.set(section='a', option='z', value='3')
c['b']['u'] = '0'
c.set('c', 'v', '0')
for i in c:
print(f'Section {i}:')
for j in c[i]:
print(f'\t{j}: {c[i][j]}')
如您所見:不再有錯誤,也無需為每個新部分名稱使用add_section()
。
但是,當然,您可以定義比假字典更有用的東西。 例如,上面給出的整個配置結構可以用一行創建:
c.read_dict(dict(a=dict(x=1, y=2, z=3), b=dict(u=0), c=dict(v=0)))
或使用替代語法:
c.read_dict({'a':{'x':1, 'y':2, 'z':3}, 'b':{'u':0}, 'c':{'v':0}})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.