私は同じ問題に直面しなければなりませんでした。configparser オブジェクトの代わりに、通常の辞書を使用することを好みます。そのため、最初にファイルを読み取り.ini
、次に configparser オブジェクトを dict に変換し、最後に文字列値から引用符 (またはアポストロフィ) を削除します。これが私の解決策です:
設定.ini
[GENERAL]
onekey = "value in some words"
[SETTINGS]
resolution = '1024 x 768'
たとえば .py
#!/usr/bin/env python3
from pprint import pprint
import preferences
prefs = preferences.Preferences("preferences.ini")
d = prefs.as_dict()
pprint(d)
設定.py
import sys
import configparser
import json
from pprint import pprint
def remove_quotes(original):
d = original.copy()
for key, value in d.items():
if isinstance(value, str):
s = d[key]
if s.startswith(('"', "'")):
s = s[1:]
if s.endswith(('"', "'")):
s = s[:-1]
d[key] = s
# print(f"string found: {s}")
if isinstance(value, dict):
d[key] = remove_quotes(value)
#
return d
class Preferences:
def __init__(self, preferences_ini):
self.preferences_ini = preferences_ini
self.config = configparser.ConfigParser()
self.config.read(preferences_ini)
self.d = self.to_dict(self.config._sections)
def as_dict(self):
return self.d
def to_dict(self, config):
"""
Nested OrderedDict to normal dict.
Also, remove the annoying quotes (apostrophes) from around string values.
"""
d = json.loads(json.dumps(config))
d = remove_quotes(d)
return d
行d = remove_quotes(d)
は、引用符を削除する責任があります。違いを確認するには、この行をコメント化またはコメント解除してください。
出力:
$ ./example.py
{'GENERAL': {'onekey': 'value in some words'},
'SETTINGS': {'resolution': '1024 x 768'}}