我正在使用Python configparser生成 config.ini 文件来存储我的脚本配置。配置是由代码生成的,但该文件的要点是,有一种外部方法可以在稍后阶段更改以编程方式生成的配置。因此,该文件需要具有良好的可读性,并且配置选项应该易于找到。 configparser 中的部分是一种很好的方法,可以确保在一个部分中,条目似乎是随机排序的。例如这段代码:
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
'shuffle': 'True',
'augment': 'True',
# [... some other options ...]
'data_layer_type' : 'hdf5',
'shape_img' : '[1024, 1024, 4]',
'shape_label' : '[1024, 1024, 1]',
'shape_weights' : '[1024, 1024, 1]'
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
生成一个 config.ini
-文件,其顺序为:
[DEFAULT]
shape_weights = [1024, 1024, 1]
# [... some of the other options ...]
shuffle = True
augment = True
data_layer_type = hdf5
# [... some of the other options ...]
shape_img = [1024, 1024, 4]
# [... some of the other options ...]
shape_label = [1024, 1024, 1]
即这些条目既不按字母顺序排列,也不按任何其他可识别的顺序排列。但我想要秩序,例如形状选项都在同一个地方,而不是分发给用户浏览...
Here据称,无序行为在 Python 3.1 中已修复,默认使用有序字典,但我正在使用 Python 3.5.2 并获取无序条目。是否需要设置一个标志或一种对字典进行排序的方法,以便(至少)产生按字母顺序排序的条目?
使用 configparser 以编程方式生成 config.ini
时,是否可以定义条目的顺序? (Python 3.5)
最佳答案
这里的问题不是 configparser
没有在内部使用 OrderedDict
,而是您正在创建一个无序文字并对其进行分配。
注意这是如何不排序的:
>>> x = {
... 'shuffle': 'True',
... 'augment': 'True',
... # [... some other options ...]
... 'data_layer_type' : 'hdf5',
... 'shape_img' : '[1024, 1024, 4]',
... 'shape_label' : '[1024, 1024, 1]',
... 'shape_weights' : '[1024, 1024, 1]'
... }
>>> for k in x:
... print(k)
...
shuffle
augment
shape_img
shape_label
shape_weights
data_layer_type
(这作为 python3.6 中的实现细节进行了更改,作为“小字典”优化的一部分(所有字典都变得有序)——由于方便,可能会标准化为 python3.7 的一部分)
此处的解决方法是确保您始终分配 OrderedDict
:
config['DEFAULT'] = collections.OrderedDict((
('shuffle', 'True'),
('augment', 'True'),
# [... some other options ...]
('data_layer_type', 'hdf5'),
('shape_img', '[1024, 1024, 4]'),
('shape_label', '[1024, 1024, 1]'),
('shape_weights', '[1024, 1024, 1]'),
))
关于python - 使用 configparser 写入文件时定义 config.ini 条目的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49722215/