我曾经也面临同样的问题。与其使用configparser对象,我更喜欢使用普通的字典。因此,首先我读取.ini
文件,然后将configparser对象转换为字典,最后我从字符串值中删除引号(或撇号)。这是我的解决方案:
preferences.ini
[GENERAL]
onekey = "value in some words"
[SETTINGS]
resolution = '1024 x 768'
example.py
from pprint import pprint
import preferences
prefs = preferences.Preferences("preferences.ini")
d = prefs.as_dict()
pprint(d)
preferences.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
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'}}
strip()
函数如果字符串以指定字符串开头或结尾,则会修改该字符串。例如,'"bar'.strip("'")
返回的是'bar'
而不是bar
。 - Jonny