本文介绍了Python:您将如何保存一个简单的设置/配置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不在乎它是JSONpickleYAML还是其他.

I don't care if it's JSON, pickle, YAML, or whatever.

我看到的所有其他实现都不兼容前向,因此,如果我有一个配置文件,则在代码中添加一个新密钥,然后加载该配置文件,它将崩溃.

All other implementations I have seen are not forwards compatible, so if I have a config file, add a new key in the code, then load that config file, it'll just crash.

有没有简单的方法可以做到这一点?

Are there any simple way to do this?

推荐答案

python中的配置文件

有几种方法可以执行此操作,具体取决于所需的文件格式.

Configuration files in python

There are several ways to do this depending on the file format required.

除非有令人信服的理由使用,否则我将使用标准的 configparser 方法另一种格式.

I would use the standard configparser approach unless there were compelling reasons to use a different format.

这样写一个文件:

from ConfigParser import SafeConfigParser

config = SafeConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')

with open('config.ini', 'w') as f:
    config.write(f)

文件格式非常简单,在方括号中标出了以下部分:

The file format is very simple with sections marked out in square brackets:

[main]
key1 = value1
key2 = value2
key3 = value3

可以从文件中提取值,如下所示:

Values can be extracted from the file like so:

from ConfigParser import SafeConfigParser

config = SafeConfigParser()
config.read('config.ini')

print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"

# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')

# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')

JSON [.json格式]

JSON数据可能非常复杂,并且具有高度可移植的优点.

JSON [.json format]

JSON data can be very complex and has the advantage of being highly portable.

将数据写入文件:

import json

config = {'key1': 'value1', 'key2': 'value2'}

with open('config.json', 'w') as f:
    json.dump(config, f)

从文件中读取数据:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)

YAML

在此答案中提供了一个基本的YAML示例.可以在 pyYAML网站上找到更多详细信息.

YAML

A basic YAML example is provided in this answer. More details can be found on the pyYAML website.

这篇关于Python:您将如何保存一个简单的设置/配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 23:53